I have tried to get the 3 level or more nested array list using self-join in mongoDB.
Collection named Book
:
_id value parent-Id
1 Chapter 1 0
2 Chapter 1.1 1
3 Chapter 1.2 1
4 Chapter 1.1.1 2
5 Chapter 1.1.2 2
6 Chapter 2 0
7 Chapter 2.1 6
Every "parent-Id" is the ID of the chapter given in the same table, if there is no parent then "parent-Id" will be 0
.
Now. I want that output structure should be like the following structure:
{
"_id": "1",
"chapter": "chater 1",
"parent-Id": "0",
"children": [
{
"_id": "2",
"chapter": "chater 1.1",
"parent-Id": "1",
"children": [
{
"_id": "4",
"chapter": "chater 1.1.1",
"parent-Id": "2",
"children": []
},
{
"_id": "5",
"chapter": "chater 1.1.2",
"parent-Id": "2",
"children": []
}
]
},
{
"_id": "3",
"chapter": "chater 1.2",
"parent-Id": "1",
"children": []
}
]
}, {
"_id": "5",
"chapter": "chater 2",
"parent-Id": "0",
"children": [
{
"_id": "7",
"chapter": "chater 2.1",
"parent-Id": "5",
"children": [
}
chapter 1
Chapter 1.1
Chapter 1.1.1
Chapter 1.1.2
Chapter 1.2
Chapter 2
Chapter 2.1
I am able to get 2 level structure but find cannot the solution for three level (i.e. chapter 1.1.1).
For level 2, I have used :
db.Book.aggregate({
$lookup: {
from: "Book",
localField: "_id",
foreignField: "parent-Id",
as: "children"
}
},
{$match: {
"parentId" : 0
}})