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
- Deconstructrefs
array field.$lookup
- JoincollectionA
(refs.id
) withcollectionB
(_id
).$project
- Decorate the document, take first name fromrefsB
array via$first
.$group
- Group by_id
and 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"
}
}
}
])