fly high
fly high

Reputation: 215

MongoDB | get max value from nested object

db.getCollection('post').find({'post_no':47}, {'comment': 1})

The resulting values are:

{
    "_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
        }
    ]
}

I want to get the maximum value 4 of the comment_group.

What can I do?

Thank you for your advice.

Upvotes: 1

Views: 1059

Answers (3)

Connor
Connor

Reputation: 1

You can alse use $reduce in the second project in Anthony Winzlet's answer.

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

Upvotes: 0

Ashh
Ashh

Reputation: 46441

You can try below aggregation

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" }
          ]
        }
      ]
    }
  }}
])

Upvotes: 1

Rubin Porwal
Rubin Porwal

Reputation: 3845

db.collection.aggregate(

    // Pipeline
    [
        // Stage 1
        {
            $unwind: {
                path: "$comment",

            }
        },

        // Stage 2
        {
            $sort: {
                "comment.comment_group": -1
            }
        },

        // Stage 3
        {
            $limit: 1
        },

    ]



);

Upvotes: 1

Related Questions