MongoDb query to get max of field inside array

find max salary in mongodb
mongodb find document with max value
mongodb find max and min java
mongodb max timestamp
get the max value of a column in mongodb
max in match mongodb
mongodb unwind
mongodb aggregate

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.

your aggregation query need $unwind for opennig to "sections" array

add your aggregation query this

{$unwind : "$sections"}

and your refactoring aggregation query like this

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

and more knowledge for $unwind : https://docs.mongodb.org/manual/reference/operator/aggregation/unwind/

$max (aggregation), How do I query an array of objects in MongoDB? REF: MongoDB Document from array with field value max Answers in Finding highest value from sub-arrays in documents and MongoDB find by max value in array of documents suggest to use sort + limit(1), however this is really slow.

You can do using simple $project stage

Something like this

db.collection.aggregate([
  { "$project": {
    "maxSectionId": {
      "$arrayElemAt": [
        "$sections",
        {
          "$indexOfArray": [
            "$sections.Id",
            { "$max": "$sections.Id" }
          ]
        }
      ]
    }
  }}
])

How to search in array of object in MongoDB?, Starting in v3.2, the $max operator is deprecated in the mongo shell. not need to hint if the find() query is an equality condition on the _id field { _id: <value> } . To query if the array field contains at least one element with the specified value, use the filter { <field> => <value> } where <value> is the element value. To query if the array field contains at least one element with the specified value, use the filter equal( <field>, <value> ) where <value> is the element value.

Replace $group with $project

In the $group stage, if the expression resolves to an array, $max does not traverse the array and compares the array as a whole.

With a single expression as its operand, if the expression resolves to an array, $max traverses into the array to operate on the numerical elements of the array to return a single value [sic]

$first (aggregation), If all documents for the $min operation have null value for the field or are missing the field, the $min operator returns null for the minimum value. Array Operand¶. In​  In this post, we will write a query using MongoDB aggregate method to get all records having Max (Highest) value for specific field. If you are new to aggregation framework, I would recommend to read following post first: MongoDB Query: Select and Filter Child Array Consider a collection school with the following documents:

$max, If <array expression> refers to a non-existing field in the input document. $​indexOfArray returns an error: If <array expression> is not an array and  This post explains how to query and fetch embedded documents from within an array field in a MongoDB collection, using the Aggregation Framework. In order to fully utilize the power of a document-based database like MongoDB, many people model their one-to-many relationships with embedded documents .

$min (aggregation), Find Restaurants with Geospatial Queries · GeoJSON Objects In previous versions of MongoDB, $max is available in the $group stage only. If some, but not all, documents for the $max operation have either a null value for the field or are if the expression resolves to an array, $max traverses into the array to operate  Use the Array Index to Query for a Field in the Embedded Document¶ Using dot notation, you can specify query conditions for field in a document at a particular index or position of the array. The array uses zero-based indexing.

$indexOfArray (aggregation), I have a document that has an array of sub-documents where the key is 7/25/​17 Kevin Adistambha MongoDB Staff Return only the largest "key" _id: '$_id', // which is the last item in the Note that adding a sorting stage would change the memory requirements (and possibly performance) of the query. 3 – Choose the array field to query. Choose previous_addresses as the field to query in the Array dropdown menu. 4 – Click on the “Drag field here or double-click” section 5 – Type the name of the array embedded field to query. The field dropdown will choose <Array Element> by default. Let’s override it by typing the name of the embedded field we want to query, “country”.

Comments
  • using $project throws exception: invalid operator '$max', code 15999
  • what version of mongodb are you using... in that case use unwind as told by @kakashi hatake but use it after your match query to limit the number of unwinded documents
  • MongoDB shell version: 3.0.7. I need max of all unwinded sections but of particular collection._id for which filter is already applied, so can't apply filter on sections.Id.
  • i meant filter with object id first then unwind like this [{"$match": {"_id": ObjectId("571c5c87faf473f40fd0317c")}},{$unwind:"$sections"}], if you unwind first all the documents irrespective of objectId doc you want will be unwinded first