与 mongodb 聚合中的 toObjectId 匹配

Match with toObjectId in mongodb Aggregate

确实坚持了一些对我来说应该很容易的事情

我基本上想做的是将 objectId 的字符串转换为 objectId 并与之匹配,但我不知道该怎么做...!

明确地说,我不能使用 { x: ObjectId(someObjectId) } 因为我想将查询序列化为 JSON

数据:

[{
  "_id": {
    "$oid": "5f37eaaae4102600180078a8"
  },
  "Details": "Something A",
  "App": {
    "$oid": "5f37cec069106932d4710ea6"
  }
},{
  "_id": {
    "$oid": "5f3860f10a9db00018f2e2e3"
  },
  "Details": "Something B",
  "App": {
    "$oid": "5f37cec069106932d4710ea6"
  }
},{
  "_id": {
    "$oid": "5f3908a7db8fd70018b19942"
  },
  "Details": "Something C",
  "App": {
    "$oid": "5f37cec069106932d4710ea7"
  }
},{
  "_id": {
    "$oid": "5f390961db8fd70018b19945"
  },
  "Details": "Something D",
  "App": {
    "$oid": "5f37cec069106932d4710ea8"
  }
}
]

并查询类似:

[
  {
    '$match': {
      'App': {
        '$eq': {
          '$toObjectId': '5f37cec069106932d4710ea8'
        }
      }
    }
  }
]

结果显然是:

{
  "_id": {
    "$oid": "5f390961db8fd70018b19945"
  },
  "Details": "Something D",
  "App": {
    "$oid": "5f37cec069106932d4710ea8"
  }
}

你可以这样做:

db.collection.aggregate([
  {
    "$match": {
      "$expr": {
        "$eq": [
          "$App",
          {
            "$toObjectId": "5f37cec069106932d4710ea8"
          }
        ]
      }
    }
  }
])

Working example