Search code examples
node.jsmongodblookupaggregation

lookup with add extra field in mongodb


My OBJ

[{
_id:XXXXXXXXXX,
role:admin
},
{
_id:XXXXXXXXXX,
role:superUser
}]

and need results using aggregation how to solve this using aggregation

[{
name:'username'
role:'test'
}

]


Solution

  • I suppose you need the following

    let db1 = db.get().collection(`temp1`);
        let db2 = db.get().collection(`temp2`);
    
        await db1.aggregate([
            {
                $lookup: {
                    from: "temp2",
                    localField: "_id",    // field in the orders collection
                    foreignField: "_id",  // field in the items collection
                    as: "users"
                }
            },
            {
                $replaceRoot: { newRoot: { $mergeObjects: [{ $arrayElemAt: ["$users", 0] }, "$$ROOT"] } }
            },
            { $project: { users: 0 } }
        ]).toArray()