我有一个这样的数组
[
{
"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,
}
]
谁能帮忙解决如何根据状态过滤数据?
最佳答案
查询
- 按名字分组
- 找到最大完整版本
- 过滤以保持完成的版本相同,未完成的版本更大
- 展开并替换 root
*例如对于 1 名称,如果您有不完整的版本 5 6 7 3 和完整的 2 3 4 ,您将得到 5 6 7 不完整的和 4 个完整的。
如果它不是您想要的,也许只需稍作改动,您就可以得到您需要的。
Playmongo (看看每个阶段做了什么把鼠标放在最后)
aggregate(
[{"$group": {"_id": "$name", "docs": {"$push": "$$ROOT"}}},
{"$set":
{"max-complete":
{"$let":
{"vars":
{"c":
{"$filter":
{"input": "$docs",
"cond": {"$eq": ["$$this.status", "complete"]}}}},
"in": {"$max": "$$c.version"}}}}},
{"$set":
{"docs":
{"$filter":
{"input": "$docs",
"cond":
{"$or":
[{"$and":
[{"$gt": ["$$this.version", "$max-complete"]},
{"$eq": ["$$this.status", "incomplete"]}]},
{"$and":
[{"$eq": ["$$this.version", "$max-complete"]},
{"$eq": ["$$this.status", "complete"]}]}]}}}}},
{"$unwind": "$docs"},
{"$replaceRoot": {"newRoot": "$docs"}}])
关于mongodb - 根据状态过滤 mongoDb 中的结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/71889602/