在外部数组中查找与 ObjectID 匹配的文档

Find documents matching ObjectIDs in a foreign array

我有一个 collection Users:

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

我还有一个collectionEvents:

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

我想要 return 给定用户参加的所有活动的列表。但是,我需要从 Events collection 执行此查询,因为这是更大查询的一部分。

我已经完成了以下问题:

我尝试了各种方法来修改上述答案以适应我的情况,但都没有成功。第三个问题中的 让我最接近,但我想过滤掉不匹配的结果,而不是让它们 return 编辑为 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 字段。