有一个体育解析器。它在一个圆圈里工作。根据某些逻辑,体育赛事被添加到数据库中。在每个解析周期中,可以将体育事件添加到数据库中,但不能添加)
我需要得到最后两个解析周期的所有体育赛事。但是,如果两个周期都有体育赛事,那么只能从最后一个周期开始。这就是问题所在。样本文件:
{
"command1": "A",
"command2": "B",
"parseCount": 0
},
{
"command1": "A",
"command2": "B",
"parseCount": 1
},
{
"command1": "A",
"command2": "B",
"parseCount": 2
},
{
"command1": "C",
"command2": "D",
"parseCount": 1
},
{
"command1": "E",
"command2": "F",
"parseCount": 2
},
因此,我应该从上面的列表中得到最后3份文件。该文档还包含字段:匹配时间和ObjectId
发布于 2021-10-05 09:00:44
如果我的理解是正确的,那么首先可以使用$sort
,然后将$first
对象放入$group
,如下所示:
我使用过$first: $$ROOT
,但如果需要,可以对对象中的每个值使用$first: value
。
此查询:
parseCount
进行排序,以获得第一位置的较高值。$group
,得到第一个对象(按顺序排列)$project
获取所需的输出值。db.collection.aggregate([
{
"$sort": {
"parseCount": -1
}
},
{
"$group": {
"_id": {
"command1": "$command1",
"command2": "$command2"
},
"object": {
"$first": "$$ROOT"
}
}
},
{
"$project": {
"_id": "$object._id",
"command1": "$object.command1",
"command2": "$object.command2",
"parseCount": "$object.parseCount"
}
}
])
示例这里
发布于 2021-10-05 09:27:56
查询
max=3
保留parseCount=3
和parseCount=2
,我们也只保留parseCount>0,在游乐场上有过滤器,如果不需要它,就移除它。command1,command2
组成,只保留最大parseCount
,您说过,我们只保留最新的,如果我们有超过1matchTime
和_id
也是保留的,因为您说您也有db.collection.aggregate([
{
"$lookup": {
"from": "collection",
"pipeline": [
{
"$group": {
"_id": null,
"maxParse": {
"$max": "$parseCount"
}
}
}
],
"as": "result"
}
},
{
"$set": {
"maxParses": {
"$let": {
"vars": {
"v0": {
"$arrayElemAt": [
"$result",
0
]
}
},
"in": "$$v0.maxParse"
}
}
}
},
{
"$unset": [
"result"
]
},
{
"$match": {
"$expr": {
"$and": [
{
"$gt": [
"$parseCount",
0
]
},
{
"$gte": [
"$parseCount",
{
"$subtract": [
"$maxParses",
1
]
}
]
}
]
}
}
},
{
"$group": {
"_id": {
"command1": "$command1",
"command2": "$command2"
},
"maxParseCount": {
"$max": {
"parseCount": "$parseCount",
"matchTime": "$matchTime",
"id": "$_id"
}
}
}
},
{
"$replaceRoot": {
"newRoot": {
"$mergeObjects": [
"$_id",
"$maxParseCount",
"$$ROOT"
]
}
}
},
{
"$project": {
"command1": 1,
"command2": 1,
"parseCount": 1,
"matchTime": 1,
"_id": "$id"
}
}
])
解释根据您的数据进行的查询
_id=2,_id=3
),但是只有_id=3
会通过,因为它有最大的parseCount[
{
"_id": 1,
"command1": "A",
"command2": "B",
"parseCount": 0,
"matchTime": 1
},
{
"_id": 2,
"command1": "A",
"command2": "B",
"parseCount": 1,
"matchTime": 2
},
{
"_id": 3,
"command1": "A",
"command2": "B",
"parseCount": 2,
"matchTime": 3
},
{
"_id": 4,
"command1": "C",
"command2": "D",
"parseCount": 1,
"matchTime": 4
},
{
"_id": 5,
"command1": "E",
"command2": "F",
"parseCount": 2,
"matchTime": 5
}
]
结果
[
{
"_id": 3,
"command1": "A",
"command2": "B",
"matchTime": 3,
"parseCount": 2
},
{
"_id": 4,
"command1": "C",
"command2": "D",
"matchTime": 4,
"parseCount": 1
},
{
"_id": 5,
"command1": "E",
"command2": "F",
"matchTime": 5,
"parseCount": 2
}
]
https://stackoverflow.com/questions/69446397
复制相似问题