I have a list of documents which contains another list as a child, which also have the = children containing same document type and it also have children array and so on. My question is I want to search document by Id which might be the parent or in the children list or its grandchildren list or grand grand child list and deeper. How can I search for that in MongoDB?
This is what my tree structure likes :
[
{
"_id": {
"$oid": "632fcf89b79445a59228851a"
},
"label": "Cow",
"children": []
},
{
"_id": {
"$oid": "632fcf8db79445a59228851b"
},
"label": "Rat",
"children": [
{
"_id": {
"$oid": "632fd378d7316cdaf81c18a7"
},
"label": "Cub",
"children": [
{
"_id": {
"$oid": "632fd378d7316cdaf81c18a8"
},
"label": "Deer",
"children": []
}
]
}
]
},
{
"_id": {
"$oid": "632fcf8eb79445a59228851c"
},
"label": "Lion",
"children": []
}
]
This is what I tried but it adds element upto 1 level, however it does not search the children list exhaustively.
var toInsert = { _id: ObjectId(), "label" : "Tiger", "children": []};
db.animal.findOneAndUpdate(
{"_id": ObjectId("632fd378d7316cdaf81c18a7")},
{
$push: {
children: toInsert
}
}
);
db.collection.find({});