【问题标题】:MongoDb aggregation query using $project and $sort使用 $project 和 $sort 的 MongoDb 聚合查询
【发布时间】:2018-05-09 22:41:32
【问题描述】:

我的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'"

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

【问题讨论】:

    标签: mongodb aggregation


    【解决方案1】:

    您需要创建一个管道来创建额外的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”?
    • 另外,更重要的是,我还有一个问题。我每天有一个文件,每个 IP 地址。我如何找到所有日子里最活跃的 ipaddress?上面的查询给了我某一天的最高值。但是我如何根据所有天的 $add 值计算最高值?
    • 任何解决方案??
    • @Charlyberthet 解决哪个问题?
    猜你喜欢
    • 2021-10-06
    • 2013-03-10
    • 1970-01-01
    • 1970-01-01
    • 2012-10-24
    • 2018-03-27
    • 2021-04-11
    • 2015-12-03
    • 1970-01-01
    相关资源
    最近更新 更多