【问题标题】:Getting a complete object via $max in mongodb aggregation在 mongodb 聚合中通过 $max 获取完整对象
【发布时间】:2014-12-03 16:06:01
【问题描述】:

如果masterID 不存在,我有一组对象需要按masterIDid 分组。在具有相同masterID 的一组对象中,我需要找到具有最高pos 属性($max: "$pos")的对象。但是,我很难获得最大化pos 的完整对象,似乎通过聚合我只能获得pos 属性,而不是整个对象。这是我使用的示例聚合,缺少$ifNullmasterID

> db.tst.aggregate([{ "$group": { "_id": "$masterID", "pos": { "$max": "$pos" } } }])

示例对象是:

> db.tst.find()
{ "_id" : ObjectId("547d6bd28e47d05a9a492e2e"), "masterID" : "master", "pos" : "453", "id" : "hallo" }
{ "_id" : ObjectId("547d6bda8e47d05a9a492e2f"), "masterID" : "master", "pos" : "147", "id" : "welt" }
{ "_id" : ObjectId("547d6be68e47d05a9a492e30"), "masterID" : "master2", "pos" : "1", "id" : "welt" }

想要的聚合结果是:

{ "_id" : ObjectId("547d6bd28e47d05a9a492e2e"), "masterID" : "master", "pos" : "453", "id" : "hallo" }
{ "_id" : ObjectId("547d6be68e47d05a9a492e30"), "masterID" : "master2", "pos" : "1", "id" : "welt" }

有没有办法通过聚合来实现这个结果,还是我需要使用$push来获取所有分组的对象并在Java代码中围绕聚合实现pos的最大化?

这个问题mongodb aggregation: How to return a the object with min/max instead of the value 表明$first$last 应该用于按pos 排序的对象,但我看不到它如何返回整个对象。

【问题讨论】:

    标签: mongodb aggregation-framework


    【解决方案1】:

    首先按pos 降序排序。这样,每个masterID 遇到的第一个文档是具有最高pos 的文档。您可以使用$$ROOT 来引用当前正在管道中处理的整个文档。

    db.tst.aggregate([
        { "$sort" : { "pos" : -1 } },
        { "$group": { 
            "_id": { $ifNull: [ "$masterID", "$_id" ] },
            "max_doc" : { "$first" : "$$ROOT" }
        } }
    ])
    

    【讨论】:

    【解决方案2】:

    如果我没有理解错,你可以试试这个:

    db.tst.aggregate([
        { "$sort" : { "pos" : -1 } },
        { 
        "$group": { 
            "_id": { $ifNull: [ "$masterID", "$id" ] },    
               "_Tempid":{$first:"$_id"},
               "masterID":{$first:{ $ifNull: [ "$masterID", "$id" ] }},
               "pos": { "$max": "$pos" },
               "id" : {$first:"$id"}
    
          }  
      },{
          $project:{
              _id:"$_Tempid",
              "masterID":1,
              "pos":1,
              id:1
          }
      }
    
    ])
    

    结果:

    {
        "result" : [ 
            {
                "_id" : ObjectId("547d6be68e47d05a9a492e30"),
                "masterID" : "master2",
                "pos" : "1",
                "id" : "welt"
            }, 
            {
                "_id" : ObjectId("547d6bd28e47d05a9a492e2e"),
                "masterID" : "master",
                "pos" : "453",
                "id" : "hallo"
            }
        ],
        "ok" : 1
    }
    

    【讨论】:

    • 您需要先按pos 排序,否则$first 值将来自的文档只是该组中自然顺序的第一个文档。
    猜你喜欢
    • 1970-01-01
    • 2021-08-24
    • 2016-05-11
    • 1970-01-01
    • 2020-03-21
    • 2019-02-07
    • 1970-01-01
    • 2011-09-03
    • 1970-01-01
    相关资源
    最近更新 更多