[
{
"_id": "1",
"name": "sanggiyo",
"gender": "Male",
"children": [
{
"name": "tono",
"gender": "Male",
"children": [
{
"name": "anton",
"gender": "male",
"children": [],
"_id": "4"
}
],
"_id": "2"
},
{
"name": "rin",
"gender": "Female",
"children": [],
"_id": "3"
}
],
"createdAt": "2022-04-17T11:14:00.648Z",
"updatedAt": "2022-04-17T11:14:16.277Z",
"__v": 0
}
]
lets say i have the id for the second nested object, or third level nested object (_id=2 or _id=3), or four level nested object (_id=4)
how to get only the document that is related to that id and not the whole document?
so far I have tried:
db.collection.aggregate([
{
$match: {
$or: [
{
"_id": "1"
},
{
"children._id": "1"
},
{
"children.children._id": "1"
}
]
}
},
{
"$replaceRoot": {
"newRoot": {
"$first": {
"$filter": {
"input": "$children",
"as": "item",
"cond": {
$eq: [
"$$item._id",
"2"
]
}
}
}
}
}
}
])
I need every id can get their own document. so in this case i expect 4 different output from 4 different case.
case 1 with id=1, i can get all data
case 2 with id=2,
{
"_id": "2",
"children": [
{
"_id": "4",
"children": [],
"gender": "male",
"name": "anton"
}
],
"gender": "Male",
"name": "tono"
}
case 3 with id=3
{
"_id": "3",
"children": [],
"gender": "Female",
"name": "rin"
}
case 4 with id=4
{
"name": "anton",
"gender": "male",
"children": [],
"_id": "4"
}
this is mongo playground for testing purpose, this way i can only get case 2 and 3 work, it fail getting case 1 and 4