【问题标题】:How to find a document with maximum field value in mongodb?如何在mongodb中找到具有最大字段值的文档?
【发布时间】:2014-07-24 15:25:43
【问题描述】:

我有一些如下形式的 Mongodb 文档:

{
    "auditedId" : "53d0f648e4b064e8d746b31c",
    "modifications" : [
        {
            "auditRecordId" : ObjectId("53d0f648e4b064e8d746b31d"),
            "modified" : "2014-07-22 18:33:05"
        },
        {
            "auditRecordId" : ObjectId("53d0f648e4b064e8d746b31e"),
            "modified" : "2014-07-24 14:15:27"
        },
        {
            "auditRecordId" : ObjectId("53d0f648e4b064e8d746b31f"),
            "modified" : "2014-07-24 12:04:24"
        }
    ]
}

对于这些文档中的每一个,我都想找到与最新修改相对应的“auditRecordId”值。在给定的示例中,我想检索

"auditRecordId" : ObjectId("53d0f648e4b064e8d746b31e")

或者,甚至更好:

{
    "auditRecordId" : ObjectId("53d0f648e4b064e8d746b31e"),
    "modified" : "2014-07-24 14:15:27"
}

有什么方法可以在不编写 map-reduce 函数的情况下做到这一点?

【问题讨论】:

    标签: mongodb mapreduce aggregation-framework


    【解决方案1】:

    只要您的文档中有一个数组,aggregate 方法就是您的朋友:)

    db.foo.aggregate([
        // De-normalize the 'modifications' array
        {"$unwind":"$modifications"}, 
        // Sort by 'modifications.modified' descending
        {"$sort":{"modifications.modified":-1}}, 
        // Pick the first one i.e., the max
        {"$limit":1}
    ])
    

    输出:

    {
            "result" : [
                    {
                            "_id" : ObjectId("53d12be57a462c7459b6f1c7"),
                            "auditedId" : "53d0f648e4b064e8d746b31c",
                            "modifications" : {
                                    "auditRecordId" : ObjectId("53d0f648e4b064e8d746b31e"),
                                    "modified" : "2014-07-24 14:15:27"
                            }
                    }
            ],
            "ok" : 1
    }
    

    为了说明$unwind 运算符,我将上述查询与$limit 一起使用。如果您有多个上述格式的文档,并且想要检索每个文档的最新修改,则必须在聚合管道中添加另一个 $group 阶段并使用 $first 运算符:

    db.foo.aggregate([
        {"$unwind":"$modifications"}, 
        {"$sort":{"modifications.modified":-1}}, 
        {"$group":{
            "_id" : "$auditedId", 
            "modifications" : {$first:"$modifications"}}}
    ])
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-01-04
      • 1970-01-01
      • 2018-04-21
      • 2013-01-04
      • 1970-01-01
      相关资源
      最近更新 更多