Reputation: 1078
My mongo collection name is home and whose having the following documents in it.
[{
"title": "Java",
"uid": "1",
"_metadata": {
"references": [{
"asssetuid": 10
}]
}
},
{
"title": "Servlet",
"uid": "2",
"_metadata": {
"references": [{
"uid": "1"
},
{
"asssetuid": 11
}
]
}
},
{
"title": "JSP",
"uid": "3",
"_metadata": {
"references": [{
"uid": "2"
}]
}
}
]
I want results like
{
"uid": 1,
"_metadata": {
"references": [{
"asssetuid": 10
}, {
"uid": "2"
},
{
"asssetuid": 11
},
{
"uid": "3"
}
]
}
}
as per we need full hierarch of a document whose uid is 1.
How we can get this result. is any way in graph lookup query to get the required result.
Upvotes: 1
Views: 288
Reputation: 22296
You want to use $graphLookup, it gives you the power to recursively search for matches which is what you're looking for:
db.home.aggregate([
{
$match: {
uid: "1"
}
},
{
"$graphLookup": {
"from": "home",
"startWith": "$uid",
"connectFromField": "uid",
"connectToField": "_metadata.references.uid",
"as": "matches"
}
},
{
$project: {
uid: 1,
_metadata: {
refrences: {
$map: {
input: "$matches",
as: "match",
in: {
uid: "$$match.uid"
}
}
}
}
}
}
])
Upvotes: 1