Mongodb: $expr 比较同一文档中同一数组的两个元素

Mongodb: $expr comparing two elements of same array in same document

我有一些文档的数组 v 恰好包含 2 个对象,其中两个数字 ab 作为属性。我想在聚合中过滤数组中两个对象具有相同 b 值的文档。

例如,有这个文件:

[
  {
    "v": [
      {
        "a": 1,
        "b": 1
      },
      {
        "a": 1,
        "b": 2
      }
    ]
  }
]

和这个查询:

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

文档不应该通过,因为它有两个 b 的差异值(12),但它最终通过了。为什么?

这里是游乐场:https://mongoplayground.net/

只要通过索引引用数组中的对象,就应该使用 $arrayElemAt 运算符。

以下查询是您要查找的内容。

db.collection.aggregate([
  {
    "$match": {
      "$expr": {
        "$eq": [
          {
            "$arrayElemAt": [
              "$v.b",
              0  // References Array Index `0`
            ]
          },
          {
            "$arrayElemAt": [
              "$v.b",
              1  // References Array Index `1`
            ]
          },
        ]
      }
    }
  }
])