MongoDB聚合查询使用$project和$sort

5
我的MongoDb集合如下:
{
    "_id" : ObjectId("5a187babdbf0a03cdca0d0bc"),
    "aggregationDate" : "2017-10-31",
    "ipaddress" : "10.65.66.184",
    "first" : {
        "count" : 3
    },
    "second" : {
        "count" : 2
    },
    "third" : {
        "count" : 3
    },
}

{
    "_id" : ObjectId("5a187babdbf0a03cdca0d0bd"),
    "aggregationDate" : "2017-10-31",
    "ipaddress" : "10.65.66.182",
    "first" : {
        "count" : 4
    },
    "second" : {
        "count" : 10
    },
    "third" : {
        "count" : 4
    },
}

{
    "_id" : ObjectId("5a187babdbf0a03cdca0d0be"),
    "aggregationDate" : "2017-10-31",
    "ipaddress" : "10.65.66.189",
    "first" : {
        "count" : 3
    },
    "second" : {
        "count" : 1
    },
    "third" : {
        "count" : 12
    },
}

我希望显示拥有第一、第二和第三计数之和最高的文档。

在这种情况下,输出应该是 -

{
    "_id" : ObjectId("5a187babdbf0a03cdca0d0bd"),
    "aggregationDate" : "2017-10-31",
    "ipaddress" : "10.65.66.182",
    "first" : {
        "count" : 4
    },
    "second" : {
        "count" : 10
    },
    "third" : {
        "count" : 4
    },
}

我只需要一个文档作为输出。
db.getCollection('foo').aggregate(
{
    $project: {
        _id: "$ipaddress",
        max: { $max: { $add: [ "$first.count", "$second.count", "$third.count"] } }
        }
 },       
 { $sort: { refCount: -1 }}
 )    

我遇到了以下异常。
"errmsg" : "exception: invalid operator '$max'"

有人可以帮我解决这个查询吗?或者我做错了什么。

1个回答

9
您需要创建一个管道,创建额外的refCount字段来保存总计数。第一个管道将是$addField,因为它允许您向文档添加新字段。使用$add运算符可以实现求和。
接下来的管道步骤将是$sort,以按照新字段的降序对文档进行排序。
最后一步$limit将返回单个文档:
db.getCollection('foo').aggregate([
    {
        "$addFields": {
            "refCount": {
                "$add": ["$first.count", "$second.count", "$third.count"]
             }
        }
    },
    { "$sort": { "refCount": -1 } },
    { "$limit": 1 }
])

谢谢伙计,你解释得很好。在这种情况下,我只能得到refCount的输出。有没有办法显示其他字段,例如“_id”:ObjectId(“5a187babdbf0a03cdca0d0bd”),“aggregationDate”:“2017-10-31”,“ipaddress”:“10.65.66.182”? - Sad Mad
另外,更重要的是,我有一个额外的问题。我有一个文档,每个IP地址,每天一个。如何找到在所有天数中最活跃的IP地址?上面的查询只给出了特定一天的最高值..但是,如何根据$add的值计算出所有天数的最高值? - Sad Mad
有任何解决方案吗? - Charly berthet
@Charlyberthet 这是解决哪个问题的? - chridam

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接