I have an array like this
[
{
"name": "CAMP-1",
"status": "incomplete",
"version": 3,
},
{
"name": "CAMP-1",
"status": "complete",
"version": 2,
},
{
"name": "CAMP-1",
"status": "complete",
"version": 1,
},
{
"name": "CAMP-2",
"status": "complete",
"version": 2,
},
{
"name": "CAMP-2",
"status": "incomplete",
"version": 1,
}
]
if the status of latest version is incomplete then both the latest incomplete and complete versions should be returned.
if the status of the latest version is complete then only that version should be returned.
I tried to group by name and status which gives the latest version of incomplete and complete object
db.collection.aggregate({
"$sort": {
"version": -1
}
},
{
"$group": {
"_id": {
"content": "$name",
"status": "$status"
},
"status": {
"$first": "$$ROOT"
},
"content": {
"$first": "$$ROOT"
}
}
},
{
"$replaceRoot": {
"newRoot": "$content"
}
})
The output which I get is
[
{
"name": "CAMP-1",
"status": "incomplete",
"version": 3,
},
{
"name": "CAMP-1",
"status": "complete",
"version": 2,
},
{
"name": "CAMP-1",
"status": "complete",
"version": 1,
},
{
"name": "CAMP-2",
"status": "incomplete",
"version": 2,
}
]
But the expected output is
[
{
"name": "CAMP-1",
"status": "incomplete",
"version": 3,
},
{
"name": "CAMP-1",
"status": "complete",
"version": 2,
},
{
"name": "CAMP-2",
"status": "complete",
"version": 2,
}
]
Can anyone please help on how to filter the data based on status?