我有一个用户架构,其中的人员字段包含viewers
属性,该属性包含一个ObjectId数组,例如作为用户集合本身的引用
{
"username": "user1",
"password": "password",
"email": "user1@gmail.com",
"people": [{
"id": 1,
"viewers": ["ObjectId....", "ObjectId...."]
},
{
"id": 2,
"viewers": ["ObjectId....", "ObjectId...."]
}
]
}
我需要对查看器中的每个元素进行$lookup
操作,问题是当我在管道下面使用时,为每个文档推送相同的查看器
{
$unwind: {
path: "$people.viewers",
preserveNullAndEmptyArrays: true
}
},
{
$lookup: {
from: "users",
localField: "people.viewers",
foreignField: "_id",
as: "people"
}
},
{
$unwind: {
path: "$viewers",
preserveNullAndEmptyArrays: true
}
},
{
$project: {
username: 1,
"viewers.username": 1
}
},
{
$group: {
_id: "$_id",
username: { $first: "$username" },
people: { $first: "$people" },
viewers: { $push: "$viewers" }
}
},
{
$project: {
username: 1,
"people.id": 1,
"people.viewers": "$viewers"
}
}
该聚合有什么问题
答案 0 :(得分:1)
您可以在mongodb 3.4 及更高版本
中尝试以下聚合User.aggregate([
{ "$unwind": { "path": "$people", "preserveNullAndEmptyArrays": true }},
{ "$lookup": {
"from": "users",
"localField": "people.viewers",
"foreignField": "_id",
"as": "people.viewers"
}},
{ "$group": {
"_id": "$_id",
"username": { "$first": "$username" },
"email": { "$first": "$email" },
"people": { "$push": "$people" }
}}
])