mongodb how to get max value from collections

MongodbMax

Mongodb Problem Overview


I have a mongodb collection like:

db.kids.find()
//results
[    {name:'tom', age:10},    {name:'alice', age:12},    ....]

I need a query to get MAX 'age' from this collection like in SQL: SELECT MAX(age) FROM kids WHERE 1

Mongodb Solutions


Solution 1 - Mongodb

As one of comments:

db.collection.find().sort({age:-1}).limit(1) // for MAX
db.collection.find().sort({age:+1}).limit(1) // for MIN

it's completely usable but i'm not sure about performance

Solution 2 - Mongodb

The performance of the suggested answer is fine. According to the [MongoDB documentation][1]:

> When a $sort immediately precedes a $limit, the optimizer can coalesce the $limit into the $sort. This allows the sort operation > to only maintain the top n results as it progresses, where n is > the specified limit, and MongoDB only needs to store n items in > memory. > > Changed in version 4.0.

So in the case of

db.collection.find().sort({age:-1}).limit(1)

we get only the highest element WITHOUT sorting the collection because of the mentioned optimization.

[1]: https://docs.mongodb.com/manual/core/aggregation-pipeline-optimization/#agg-sort-limit-coalescence "MongoDB documentation"

Solution 3 - Mongodb

what about using aggregate framework:

db.collection.aggregate({ $group : { _id: null, max: { $max : "$age" }}});

Solution 4 - Mongodb

you can use group and max:

db.getCollection('kids').aggregate([
    {
        $group: {
            _id: null,
            maxQuantity: {$max: "$age"}
        }
    }
])

Solution 5 - Mongodb

Folks you can see what the optimizer is doing by running a plan. The generic format of looking into a plan is from the MongoDB documentation . i.e. Cursor.plan(). If you really want to dig deeper you can do a cursor.plan(true) for more details.

Having said that if you have an index, your db.col.find().sort({"field":-1}).limit(1) will read one index entry - even if the index is default ascending and you wanted the max entry and one value from the collection.

In other words the suggestions from @yogesh is correct.

Thanks - Sumit

Solution 6 - Mongodb

db.collection.findOne().sort({age:-1}) //get Max without need for limit(1)

Solution 7 - Mongodb

Simple Explanation, if you have mongo query Response something like below - and you want only highest value from Array-> "Date"

{
  "_id": "57ee5a708e117c754915a2a2",
  "TotalWishs": 3,
  "Events": [
    "57f805c866bf62f12edb8024"
  ],
  "wish": [
    "Cosmic Eldorado  Mountain Bikes, 26-inch (Grey/White)",
    "Asics Men's Gel-Nimbus 18 Black, Snow and Fiery Red Running Shoes - 10 UK/India (45 EU) (11 US)",
    "Suunto Digital Black Dial Unisex Watch - SS018734000"
  ],
  "Date": [
    "2017-02-13T00:00:00.000Z",
    "2017-03-05T00:00:00.000Z"
  ],
  "UserDetails": [
    {
      "createdAt": "2016-09-30T12:28:32.773Z",
      "jeenesFriends": [
        "57edf8a96ad8f6ff453a384a",
        "57ee516c8e117c754915a26b",
        "58a1644b6c91d2af783770b0",
        "57ef4631b97d81824cf54795"
      ],
      "userImage": "user_profile/Male.png",
      "email": "[email protected]",
      "fullName": "Roopak Kapoor"
    }
  ],
  
},

***Then you have add

> Latest_Wish_CreatedDate: { $max: "$Date"},

somthing like below-

{ 
				$project : { _id: 1,
							 TotalWishs : 1 ,
							  wish:1 ,
							   Events:1, 
							   Wish_CreatedDate:1,
							   Latest_Wish_CreatedDate: { $max: "$Date"},
							} 
			} 

And Final Query Response will be below

{
  "_id": "57ee5a708e117c754915a2a2",
  "TotalWishs": 3,
  "Events": [
    "57f805c866bf62f12edb8024"
  ],
  "wish": [
    "Cosmic Eldorado  Mountain Bikes, 26-inch (Grey/White)",
    "Asics Men's Gel-Nimbus 18 Black, Snow and Fiery Red Running Shoes - 10 UK/India (45 EU) (11 US)",
    "Suunto Digital Black Dial Unisex Watch - SS018734000"
  ],
  "Wish_CreatedDate": [
    "2017-03-05T00:00:00.000Z",
    "2017-02-13T00:00:00.000Z"
  ],
  "UserDetails": [
    {
      "createdAt": "2016-09-30T12:28:32.773Z",
      "jeenesFriends": [
        "57edf8a96ad8f6ff453a384a",
        "57ee516c8e117c754915a26b",
        "58a1644b6c91d2af783770b0",
        "57ef4631b97d81824cf54795"
      ],
      "userImage": "user_profile/Male.png",
      "email": "[email protected]",
      "fullName": "Roopak Kapoor"
    }
  ],
  "Latest_Wish_CreatedDate": "2017-03-05T00:00:00.000Z"
},

Solution 8 - Mongodb

For max value, we can write sql query as

select age from table_name order by age desc limit 1

same way we can write in mongodb too.

db.getCollection('collection_name').find().sort({"age" : -1}).limit(1); //max age
db.getCollection('collection_name').find().sort({"age" : 1}).limit(1); //min age

Solution 9 - Mongodb

You can also achieve this through aggregate pipeline.

db.collection.aggregate([{$sort:{age:-1}}, {$limit:1}])

Solution 10 - Mongodb

Below query will get you max age without other fields,

db.collection.find({}, {"_id":0, "age":1}).sort({age:-1}).limit(1)

Below query will get you max age along with all the collection fields,

db.collection.find({}).sort({age:-1}).limit(1)

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionHossain KhademianView Question on Stackoverflow
Solution 1 - MongodbHossain KhademianView Answer on Stackoverflow
Solution 2 - MongodbpopolvarView Answer on Stackoverflow
Solution 3 - MongodbdierView Answer on Stackoverflow
Solution 4 - Mongodblvks2012View Answer on Stackoverflow
Solution 5 - MongodbSumit SView Answer on Stackoverflow
Solution 6 - MongodbHishamView Answer on Stackoverflow
Solution 7 - MongodbShashwat GuptaView Answer on Stackoverflow
Solution 8 - MongodbKankatala KrishnaView Answer on Stackoverflow
Solution 9 - Mongodbsunny prakashView Answer on Stackoverflow
Solution 10 - MongodbShubham SaxenaView Answer on Stackoverflow