我是MongoDB的新手,我有两个这样的集合:
第一个集合名称是
db.a.find()
{
"_id": "1234",
"versions": [{
"owner_id": ObjectId("100000"),
"versions": 1,
"type" : "info",
"items" : ["item1","item3","item7"]
},
{
"owner_id": ObjectId("100001"),
"versions": 2,
"type" : "bug",
"OS": "Ubuntu",
"Dependencies" : "Trim",
"items" : ["item1","item7"]
}
]}
第二个集合名称是b
db.b.find()
{
"_id": ObjectId("100000"),
"email": "abc@xyz.com"
} {
"_id": ObjectId("100001"),
"email": "bbc@xyz.com"
}
预期输出为:
{
"_id": "1234",
"versions":[{
"owner_id": "abc@xyz.com",
"versions": 1,
"type" : "info",
"items" : ["item1","item3","item7"]
},
{
"owner_id": "bbc@xyz.com",
"versions": 2,
"type" : "bug",
"OS": "Ubuntu",
"Dependencies" : "Trim",
"items" : ["item1","item7"]
}
] }
要求:版本的每个文档中的字段都未修复, 示例:版本[0] 有4个键值对,版本[1] 有6个键值对。 所以我正在寻找一个可以用电子邮件替换 owner_id 的查询,并将所有其他文件保存在输出中。
我试过了:
db.a.aggregate(
[
{$unwind:"$versions"},
{$lookup : {from : "b", "localField":"versions.owner_id", "foreignField":"_id", as :"out"}},
{$project : {"_id":1, "versions.owner_id":{$arrayElemAt:["$out.email",0]}}},
{$group:{_id:"$_id", versions : {$push : "$versions"}}}
]
).pretty()
请帮忙。
谢谢!!!
答案 0 :(得分:1)
而不是$project管道阶段使用$addFields。
示例:
db.a.aggregate([
{ $unwind: "$versions" },
{
$lookup: {
from: "b",
localField: "versions.owner_id",
foreignField: "_id",
as: "out"
}
},
{
$addFields: {
"versions.owner_id": { $arrayElemAt: ["$out.email",0] }
}
},
{ $group: { _id: "$_id", versions: { $push: "$versions" } } }
]).pretty()