How to lookup with object by reference id and other properties.
collectionA
{
_id: ObjectId("6013859ba0c3120034d08bfa"),
name: "A1",
refs:[
{id: ObjectId("6013859ba0c3120034d08bfb"), text: "ABC"},
{id: ObjectId("6013859ba0c3120034d08bfc"), text: "DEF"}
]
}
collectionB
{
_id: ObjectId("6013859ba0c3120034d08bfb"),
name: "B1"
}
{
_id: ObjectId("6013859ba0c3120034d08bfc"),
name: "B2"
}
Expected Result
{
_id: ObjectId("6013859ba0c3120034d08bfa"),
name: 'A1',
refs:[
{id: ObjectId("6013859ba0c3120034d08bfb"), name: "B1", text: "ABC"},
{id: ObjectId("6013859ba0c3120034d08bfc"), name: "B2", text: "DEF"}
]
}
CodePudding user response:
$unwind- Deconstructrefsarray field.$lookup- JoincollectionA(refs.id) withcollectionB(_id).$project- Decorate the document, take first name fromrefsBarray via$first.$group- Group by_idand generate (required) fields for the document(s).
db.collectionA.aggregate([
{
$unwind: "$refs"
},
{
"$lookup": {
"from": "collectionB",
"localField": "refs.id",
"foreignField": "_id",
"as": "refsB"
}
},
{
$project: {
_id: 1,
name: 1,
refs: {
id: "$refs.id",
text: "$refs.text",
name: {
$first: "$refsB.name"
}
}
}
},
{
$group: {
_id: "$_id",
name: {
$first: "$name"
},
refs: {
$push: "$refs"
}
}
}
])
