【问题标题】:MongoDB | get max value from nested objectMongoDB |从嵌套对象中获取最大值
【发布时间】:2018-10-12 09:47:46
【问题描述】:
db.getCollection('post').find({'post_no':47}, {'comment': 1})

结果值为:

{
    "_id" : ObjectId("5bc05c038e798ccb0309658b"),
    "comment" : [ 
        {
            "comment_no" : 112
        }, 
        {
            "comment_no" : 113,
            "comment_group" : 1
        }, 
        {
            "comment_no" : 116,
            "comment_group" : 2
        }, 
        {
            "comment_no" : 117,
            "comment_group" : 3
        }, 
        {
            "comment_group" : 4,
            "comment_no" : 118
        }
    ]
}

我想得到comment_group的最大值4。

我能做什么?

感谢您的建议。

【问题讨论】:

    标签: mongodb aggregation-framework max


    【解决方案1】:
    db.collection.aggregate(
    
        // Pipeline
        [
            // Stage 1
            {
                $unwind: {
                    path: "$comment",
    
                }
            },
    
            // Stage 2
            {
                $sort: {
                    "comment.comment_group": -1
                }
            },
    
            // Stage 3
            {
                $limit: 1
            },
    
        ]
    
    
    
    );
    

    【讨论】:

      【解决方案2】:

      你可以试试下面的聚合

      db.collection.aggregate([
        { "$project": {
          "comment": {
            "$map": {
              "input": "$comment",
              "in": {
                "comment_no": "$$this.comment_no",
                "comment_group": { "$ifNull": [ "$$this.comment_group", 0 ] }
              }
            }
          }
        }},
        { "$project": {
          "comment": {
            "$arrayElemAt": [
              "$comment",
              {
                "$indexOfArray": [
                  "$comment.comment_group",
                  { "$max": "$comment.comment_group" }
                ]
              }
            ]
          }
        }}
      ])
      

      【讨论】:

      • 谢谢!!我将它从“comment_no”更改为“comment_group”并应用了它。但结果不正确。最大值是3,不是4。好像comment_group值并不是所有对象都存在。我该如何补充?
      • 更新了我的答案
      • 第三种方法有效。这很有帮助。谢谢!!
      • @flyhigh 被接受的答案不会给你带来性能。
      • 您的答案是否显示出更好的性能?你能解释更多吗?
      【解决方案3】:

      您也可以在 Anthony Winzlet 的回答中的第二个项目中使用 $reduce

      {
        "$project": {
          "comment": {
            '$reduce': {
              'input': '$comment',
              'initialValue': {'$arrayElemAt': ['$comment', 0]},
              'in': {
                '$cond': {
                  'if': {'$gt': ['$$this.comment_group', '$$value.comment_group']},
                  'then': '$$this',
                  'else': '$$value'
                }
              }
            }
          }
        }
      }
      

      【讨论】:

        猜你喜欢
        • 2019-05-08
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2013-10-11
        • 1970-01-01
        相关资源
        最近更新 更多