我有一个这样的数组
[
{
"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,
}
]
如果最新版本的状态为不完整,则应返回最新的不完整版本和完整版本.
如果最新版本的状态为"完成",则只应返回该版本.
我试着按名字和状态分组,这给出了最新版本的不完整和完整对象
db.collection.aggregate({
"$sort": {
"version": -1
}
},
{
"$group": {
"_id": {
"content": "$name",
"status": "$status"
},
"status": {
"$first": "$$ROOT"
},
"content": {
"$first": "$$ROOT"
}
}
},
{
"$replaceRoot": {
"newRoot": "$content"
}
})
我得到的结果是
[
{
"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,
}
]
但预期的输出是
[
{
"name": "CAMP-1",
"status": "incomplete",
"version": 3,
},
{
"name": "CAMP-1",
"status": "complete",
"version": 2,
},
{
"name": "CAMP-2",
"status": "complete",
"version": 2,
}
]
有谁能帮助我们根据状态过滤数据吗?