You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

DocumentDB 5.0替代MongoDB arrayElemAt/expr/eq的查询方案

DocumentDB 5.0:查询passengers数组前两个元素邮箱相同的文档

问题背景

我的DocumentDB中有如下结构的文档:

{
  "_id": {
    "$oid": "5bc7a1d14cedfd0006445b10"
  },
  "externalId": {
    "$numberLong": "70285"
  },
  "passengers": [
    {
      "_id": {
        "$numberLong": "3757"
      },
      "name": "abc",
      "email": "abc@xyz.com"
    },
    {
      "_id": {
        "$numberLong": "398"
      },
      "name": "abc n",
      "email": "abc@xyz.com"
    }
  ]
}

我需要筛选出passengers数组前两个元素邮箱地址相同的文档。原本在MongoDB中可以使用以下查询,但该语句在DocumentDB 5.0中无法生效:

db.collection.find({
  $expr: {
    $eq: [
      {
        $arrayElemAt: [
          "$passengers.email",
          0
        ]
      },
      {
        $arrayElemAt: [
          "$passengers.email",
          1
        ]
      }
    ]
  }
})

可用的替代方案

DocumentDB 5.0对$arrayElemAt结合嵌套数组字段的支持有限,你可以使用以下两种兼容的方式实现需求:

1. 使用$where语句

通过直接访问数组索引对应的字段进行对比:

db.collection.find({
  $where: "this.passengers[0].email === this.passengers[1].email"
})

注意:$where会逐文档执行JavaScript逻辑,数据量较大时性能会受影响,适合小数据集场景。

2. 使用聚合管道(推荐)

利用DocumentDB支持的数组索引直接访问语法,在聚合的$match阶段完成过滤:

db.collection.aggregate([
  {
    $match: {
      $expr: {
        $eq: [
          "$passengers.0.email",
          "$passengers.1.email"
        ]
      }
    }
  }
])

这种方式性能更优,适合大规模数据查询,是更推荐的方案。

内容的提问来源于stack exchange,提问作者Sandeep Nair

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.14 22:25:31