我有一个包含帖子和评论的嵌入式文档。注释是带有用户详细信息commentedby
的嵌入式文档。用户名很有可能经常更改。因此,每次访问评论时都需要查找用户的值。
是否有使用mongo查询执行此操作的有效方法。 我不喜欢使用unwind ,因为我将在重新分组时失去其他发布参数
{
"PostId":"Post001",
"Comments":[
{"_id": "001",
"CommentedBy":{
"_id":"User001",
"Name":"UserName001",
"email":"user001@eg.com"
}
},
{"_id": "002",
"CommentedBy":{
"_id":"User002",
"Name":"UserName002",
"email":"user001@eg.com"
}
},
{"_id": "003",
"CommentedBy":{
"_id":"User003",
"Name":"UserName003",
"email":"user001@eg.com"
}
}
]
}
用户文档不仅包含用户名和ID。使用多次查找可能最终会多次引用User001
。
预期结果
{
"PostId":"Post001",
"Comments":[
{"_id": "001",
"CommentedBy":{
"_id":"User001",
"Name":"UserName001",
"email":"user001@eg.com",
"Group":"Marketing",
"Location":"India" }
},
{"_id": "002",
"CommentedBy":{
"_id":"User002",
"Name":"UserName002",
"email":"user002@eg.com",
"Group":"Engineering",
"Location":"USA"
}
},
{"_id": "003",
"CommentedBy":{
"_id":"User002",
"Name":"UserName002",
"email":"user002@eg.com",
"Group":"Engineering",
"Location":"USA"
}
}
]
}
UserDocument看起来像这样
User = [
{
"_id":"User001",
"Name":"UserName001",
"email":"user001@eg.com",
"Group":"Marketing",
"Location":"USA"
},
{
"_id":"User002",
"Name":"UserName002",
"email":"user002@eg.com",
"Group":"Engineering",
"Location":"USA"
}
...
...
]
我尝试过的查询
db.getCollection('Posts').aggregate([
{$lookup:{
from: "User",
localField: "Comments.CommentedBy._id",
foreignField: "_id",
as: "Comments.CommentedBy"
}},
])
User002
时会进行某种优化,因为它需要被查询两次。