I created categories in mongoDB using node, Added parent property to every insert to determine which is the parent category.
[{ _id: 5889a06f274afdfd6f2bf249,
cat_id: 1,
title: 'Parent Category',
description: '',
parent: null,
status: 1}]
[{ _id: 5889a06f274afdfd6f2bf249,
cat_id: 1,
title: 'Child Category',
description: '',
parent: 1,
status: 1}]
Now the output json should be using node when I query using db.find() method of mongoDB.
{
obj: [
{
_id: "5889a06f274afdfd6f2bf249",
cat_id: 1,
title: "Parent Category",
description: "",
parent: null,
status: 1,
subcategories: [
{
_id: "5889a06f274afdfd6f2bf249",
cat_id: 1,
title: "Child Category",
description: "",
parent: 1,
status: 1
}
]
}
]}
You can try something like below.
$startWith expression value for each input document is matched against the connectToField.
For each matching document, the connectFromField value is matched recursively against the connectToField value in the collection.
Collection
{ "_id" : 1, "cat_id" : 1, "title" : "Parent Category", "parent" : null }
{ "_id" : 2, "cat_id" : 2, "title" : "Child Category", "parent" : 1 }
{ "_id" : 3, "cat_id" : 3, "title" : "Sub Child Category", "parent" : 2 }
Query
Categories.aggregate([{
$graphLookup: {
from: "categories",
startWith: "$cat_id",
connectFromField: "cat_id",
connectToField: "parent",
as: "subCategory"
}
}], callback)
Output
{
"_id": 1,
"cat_id": 1,
"title": "Parent Category",
"parent": null,
"subCategory": [{
"_id": 3,
"cat_id": 3,
"title": "Sub Child Category",
"parent": 2
}, {
"_id": 2,
"cat_id": 2,
"title": "Child Category",
"parent": 1
}]
} {
"_id": 2,
"cat_id": 2,
"title": "Child Category",
"parent": 1,
"subCategory": [{
"_id": 3,
"cat_id": 3,
"title": "Sub Child Category",
"parent": 2
}]
} {
"_id": 3,
"cat_id": 3,
"title": "Sub Child Category",
"parent": 2,
"subCategory": []
}