我有这样一个数组
[
{
"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,
}
]有谁能帮助我们如何根据状态过滤数据?
发布于 2022-04-16 00:52:16
查询
*例如,对于一个名称,如果您有不完整的版本5 6 7 3和完整2 3 4,您将得到5 6 7不完成和4完成。
如果这不是你想要的,也许通过小小的改变,你就能得到你所需要的。
花花果 (看看每一个阶段都会把鼠标放到它的末端)
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"}}])https://stackoverflow.com/questions/71889602
复制相似问题