1
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.

3 Answers 3

1
db.collection.aggregate(

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

            }
        },

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

        // Stage 3
        {
            $limit: 1
        },

    ]



);
Sign up to request clarification or add additional context in comments.

Comments

1

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

8 Comments

Thank you!! I changed it from 'comment_no' to 'comment_group' and applied it. But The result is incorrect. The maximum value is 3, not 4. It seems that the comment_group value does not exist in all objects. How can I supplement this?
Updated my answer
The third method works. It was very helpful. Thank you!!
@flyhigh Well Accepted answer won't give you the performance.
Do your answers show better performance? Could you explain more?
|
0

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'
          }
        }
      }
    }
  }
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.