Mongodb 聚合:用另一个集合的匹配值替换一个集合的值

Mongodb Aggregate : replace value of one collection with matching value of other collection

我是 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"]
    }
] }

要求:版本的每个文档里面的字段是不固定的, 示例:versions[0] 有 4 个键值对,versions[1] 有 6 个键值对。 所以我正在寻找一个可以将 owner_id 替换为 email 的查询,并在输出中保留所有其他文件。

我试过了:

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()

请帮忙。

谢谢!!!

而不是$project pipeline stage use $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()