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

问题描述 投票:0回答:1

我有一个集合Users

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

我有另一个集合Events

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

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

我已经完成了以下问题:

我已经尝试了各种方法修改上述答案以适应我的情况,但一直没有成功。来自第三个问题的second answer让我最接近,但我想过滤掉不匹配的结果,而不是让它们返回值为0。

我想要的输出:

[
  {
    _id: "2cd9fjdkfsld"
    title: "Some Event Attended"
  },
]
mongodb mongodb-query aggregation-framework mongojs
1个回答
1
投票

一种选择是这样的:

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字段。

© www.soinside.com 2019 - 2024. All rights reserved.