Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MongoDb query to get max of field inside array

How to get the maximum of sections.Id in below document where collection._id = some parameter

{
    "_id" : ObjectId("571c5c87faf473f40fd0317c"),
    "name" : "test 1",
    "sections" : [ 
        {
             "Id" : 1,
             "name" : "first section"
        }, 
        {
            "Id" : 2,
            "name" : "section 2"
        }, 
        {
            "Id" : 3,
            "name" : "section 3"
        }
}

I have tried below

db.collection.aggregate(
[
    {
        "$match": {
            "_id": ObjectId("571c5c87faf473f40fd0317c")
        }
    },
    {
        "$group" : {
            "_id" : "$_id",
            "maxSectionId" : {"$max" : "$sections.Id"}
        }
    }
]);

But instead of returning max int single value it is returning an array of all Ids in sections array.

Further same query when executed in node.js it returns an empty array.

like image 710
Arvind Singh Avatar asked Dec 05 '22 00:12

Arvind Singh


1 Answers

You can do using simple $project stage

Something like this

db.collection.aggregate([
  { "$project": {
    "maxSectionId": {
      "$arrayElemAt": [
        "$sections",
        {
          "$indexOfArray": [
            "$sections.Id",
            { "$max": "$sections.Id" }
          ]
        }
      ]
    }
  }}
])
like image 86
Ashh Avatar answered Jan 01 '23 07:01

Ashh