Mongodb $lookup在$group之后嵌套的外部id
我想在$lookup之后用真实用户属性替换外部用户ID,我的数据:Mongodb $lookup在$group之后嵌套的外部id,mongodb,mongodb-query,Mongodb,Mongodb Query,我想在$lookup之后用真实用户属性替换外部用户ID,我的数据: "comments" : [ { "user_Id" : ObjectId("aaa"), "content" : "aaaa", "rep" : [ { "user_Id" : ObjectId("bbb"), "comment"
"comments" : [
{
"user_Id" : ObjectId("aaa"),
"content" : "aaaa",
"rep" : [
{
"user_Id" : ObjectId("bbb"),
"comment" : "bbbb",
},
{
"user_Id" : ObjectId("ccc"),
"comment" : "cccc",
}
]
},
{
"user_Id" : ObjectId("ddd"),
"content" : "ddd",
"rep" : [ ]
}
]
用户集合:
"users" : [
{
"_id" : ObjectId("aaa"),
"name" : "user1",
"email" : "test1@test.com",
},
{
"_id" : ObjectId("bbb"),
"username" : "user2",
"email" : "test2@test.com",
}
]
我想做的是:
"comments" : [
{
"user" : {
"_id" : ObjectId("aaa"),
"name" : "user1",
"email" : "test1@test.com",
}
"content" : "aaaa",
"rep" : [
{
"userId" : {
"_id" : ObjectId("bbb"),
"username" : "user2",
"email" : "test2@test.com",
},
"comment" : "bbbb",
},
{
"user" : {
"_id" : ObjectId("aaa"),
"name" : "user1",
"email" : "test1@test.com",
},
"comment" : "cccc",
}
]
},
{
"user" : {
"_id" : ObjectId("bbb"),
"username" : "user2",
"email" : "test2@test.com",
},
"content" : "ddd",
"rep" : [ ]
}
]
现在,我设法从外部id获取我的用户信息,但我也疯狂地尝试在回复中获取用户对象,我尝试在分组后进行分组,但没有做任何事情,这就是我所做的:
db.pages.aggregate([
{
$match: { _id: ObjectId('5db599f3fffdee1c822269e0b3') }
},
{
$project: {
comments: 1,
}
},
{ $unwind: '$comments' },
{
$lookup:
{
from: 'users',
localField: 'comments.user_Id',
foreignField: '_id',
as: 'us'
}
},
{ $unwind: '$us' },
{
$group: {
_id: {
user: {
id: '$us._id',
name: '$us.username',
email: '$us.email',
},
comments: {
comment: '$comments.comment',
rep: '$comments.rep'
},
}
}
}
]).pretty()
您还可以将页面集合示例数据添加到问题中吗?当然可以
页面:[{title:aaa,content:aaa,author:ObjectId(aaa),comments:…(如第一个代码块所示)}]