在外国数组中查找与objectid匹配的文档



我有一个集合Users

{
  _id: "5cds8f8rfdshfd"
  name: "Ted"
  attending: [ObjectId("2cd9fjdkfsld")]
}

我有另一个集合Events

{
  _id: "2cd9fjdkfsld"
  title: "Some Event Attended"
},
{
  _id: "34dshfj29jg"
  title: "Some Event NOT Attended"
}

我想返回给定用户参加的所有事件列表。但是,我需要从Events集合中进行此查询,因为这是较大查询的一部分。

我遇到了以下问题:

  • $在数组中的objectid上查找 - 这个问题将数组作为本地字段;我的是外国
  • 当外国字段是一系列对象时 - 数组是对象本身
  • 当外国字段是数组
  • 时,MongoDB查找

我尝试了各种修改上述答案以适应我的情况,但没有成功。第三个问题的第二个答案使我最接近,但我想滤除不匹配的结果,而不是以0的值返回。

我所需的输出:

[
  {
    _id: "2cd9fjdkfsld"
    title: "Some Event Attended"
  },
]

一个选项就是这样:

db.getCollection('Events').aggregate({
    $lookup: // join
    {
        from: "Users", // on Users collection
        let: { eId: "$_id" }, // keep a local variable "eId" that points to the currently looked at event's "_id"
        pipeline: [{
            $match: { // filter where
                "_id": ObjectId("5c6efc937ef75175b2b8e7a4"), // a specific user
                $expr: { $in: [ "$$eId", "$attending" ] } // attends the event we're looking at
            }
        }],
        as: "users" // push all matched users into the "users" array
    }
}, {
    $match: { // remove events that the user does not attend
        "users": { $ne: [] }
    }
})

您显然可以通过添加另一个投影(如果需要)来摆脱users字段。

最新更新