I have a set of nested object documents that I need to retrieve and group based on the nested objects with empty arrays using aggregation.
Let me provide a more detailed explanation-- suppose my collection consists of the following documents --
Document 1
{
"_id": "17202155",
"completed": [
"cse331",
"cse312"
],
"incompleted": [
{
"name": "math",
"preReq": []
},
{
"name": "science",
"preReq": [
"bang",
"eng",
"math"
]
},
{
"name": "astronomy",
"preReq": [
"bang",
"eng",
"science"
]
}
]
}
Document 2
{
"_id": "17202157",
"completed": [
"cse331",
"cse312"
],
"incompleted": [
{
"name": "math",
"preReq": []
},
{
"name": "science",
"preReq": []
},
{
"name": "astronomy",
"preReq": [
"bang",
"eng",
"science"
]
}
]
}
I aim to fetch the documents grouped by ID where the object contains an empty array. This would result in the following output --
{
"_id": "17202155",
"incompleted": [
{
"name": "math",
"preReq": []
}
]
},
{
"_id": "17202157",
"incompleted": [
{
"name": "math",
"preReq": []
},
{
"name": "science",
"preReq": []
}
]
}
I attempted to use the provided code, but it didn't work. Being new to MongoDB, I request your assistance--
#my code-
db.collection.aggregate({
"$unwind": "$_id"
},
{
"$group":{"_id": "$incompleted",}
},
{
"$match": {
"_id.preReq": {
$size: 0
}
}
},
)