Mongodb Aggregate : replace value of one collectio

2020-06-29 07:43发布

问题:

I am new to MongoDB, I have two collections like this :

1st collection name is a

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

2nd Collection name is b

db.b.find()

 {
    "_id": ObjectId("100000"),
    "email": "abc@xyz.com"
  } {
    "_id": ObjectId("100001"),
    "email": "bbc@xyz.com"
 }

Expected output is:

{
"_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"]
    }
] }

Requirement: fields inside each document of versions are not fixed, Example : versions[0] have 4 key-value pair and versions[1] have 6 key-value pair. so I am looking a query which can replace owner_id with email keeping all other filed in output.

I tried :

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

Please help.

Thank You!!!

回答1:

Instead of $project pipeline stage use $addFields.

Example:

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