So I have a document and model that is structured like this
{
"name":"root",
"children":[
{
"_id":1,
"name":"A",
"children":[
{
"_id":2,
"name":"A child1",
"children":[
]
}
]
},
{
"_id":3,
"name":"B",
"children":[
{
"_id":4,
"name":"B child1",
"children":[
{
"_id":5,
"name":"B1 child1",
"children":[
{
"_id":6,
"name":"B1-1 child1",
"children":[
]
}
]
}
]
}
]
}
]
}
if I wanted to find children of A or B of root I can go
db.treeModel.find({'treeModel.children': 1}
db.treeModel.find({'treeModel.children': 3}
however, it doesn't seem to work on the ids of the children of the individual nodes. Does mongo or mongoose support this or am I missing an operator?
CodePudding user response:
you need _id in the path (and to omit "treeModel") like:
db.treeModel.find({'children._id': 1})
db.treeModel.find({'children._id': 3})
keep in mind that this will still return the entire parent document
mongo/mongoose does not support recursive nested document lookups in a find directly. if you have max depth, you can use multiple $or conditions
db.treeModel.find({
$or: [
{ 'children._id': 1 },
{ 'children.children._id': 1 },
{ 'children.children.children._id': 1 },
]
});
otherwise for recursive nested, you may need to redo you data structures so you can use $graphLookup in an aggregation