【问题标题】:Find documents matching ObjectIDs in a foreign array在外部数组中查找与 ObjectID 匹配的文档
【发布时间】:2019-02-21 19:01:57
【问题描述】:

我有一个收藏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】:

一个选项是这样的:

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

【讨论】:

  • 哪个标题?活动名称?您可以简单地添加另一个管道阶段$project: { "title": 0 }
  • 对不起,我在远程服务器上测试。是的,事件标题...向管道添加投影不会做任何事情。我需要先放松一下吗?
  • 您的结果文档是什么样的?如果它在根级别上有一个title 字段,并且您在管道末尾添加了上面提到的投影阶段,那么这肯定会从输出中消除该字段。
  • 哦,原来如此;我以为我已经尝试过了,但我想我仍然在远程。谢谢。
猜你喜欢
  • 2019-01-10
  • 2015-12-03
  • 1970-01-01
  • 2023-04-02
  • 1970-01-01
  • 1970-01-01
  • 2016-02-17
  • 2019-07-16
  • 1970-01-01
相关资源
最近更新 更多