我有一个收藏集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"
},
]
答案 0 :(得分: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
字段。