I have created mongo playground and I’m expecting below output.
Note: Relationship between parent and address uses DBRef.
Expected Output:
{
"_id": ObjectId("64a67f2fdbe7c36e2e6c15c6"),
"name": {
"type": "permenant"
},
"address": "permenant address 1",
"parent":{
"_id": ObjectId("64a67f32dbe7c36e2e6c15c8"),
"name": {
"user": "xyz"
},
"data": {
"age": "55"
}
}
}
This one should be simpler than the last one, you just need to have a lookup stage and then $unwind to convert the array to a single entry.
[
{
"_id": ObjectId("64a67f2fdbe7c36e2e6c15c6"),
"address": "permenant address 1",
"name": {
"type": "permenant"
},
"parent": {
"_id": ObjectId("64a67f32dbe7c36e2e6c15c8"),
"data": {
"age": "55"
},
"name": {
"user": "xyz"
}
}
},
{
"_id": ObjectId("64a67f2fdbe7c36e2e6c15c7"),
"address": "permenant address 2",
"name": {
"type": "secondary"
},
"parent": {
"_id": ObjectId("64a67f32dbe7c36e2e6c15c8"),
"data": {
"age": "55"
},
"name": {
"user": "xyz"
}
}
},
{
"_id": ObjectId("64a67f2fdbe7c36e2e6c15c3"),
"address": "other address 2",
"name": {
"type": "other"
},
"parent": {
"_id": ObjectId("64a67f32dbe7c36e2e6c15c8"),
"data": {
"age": "55"
},
"name": {
"user": "xyz"
}
}
}
]
db.Address.aggregate([
{
$lookup: {
from: "Parent",
localField: "parent.id",
foreignField: "_id",
as: "parent"
}
},
{
$unwind: "$parent"
},
])
I’d recommend running through the Mongo University courses on these stages to get a good handle of them:
If from a relational background:
2 Likes
Yes, that works but struggling with DBRef(‘Parent’, ‘64a67f32dbe7c36e2e6c15c8’)
Which is actual in mongodb.
It worked after adding $ sign
localField: “parent.$id”,
system
(system)
Closed
5
This topic was automatically closed 5 days after the last reply. New replies are no longer allowed.