Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

mongodb how to get max value from collections

Tags:

mongodb

max

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

like image 748
Hossain Khademian Avatar asked Aug 18 '15 15:08

Hossain Khademian


People also ask

How does MongoDB define maximum number of documents in collection?

Unless you create a capped collection, there is no limit to the number of documents in a collection. There is a 16MB limit to the size of a document (use gridfs in this situation) and limits in the storage engine for the size of the database and data.

How does MongoDB calculate min max?

You need to use the . aggregate() method for it to work. For very large collections aggregating pipeline can be very slow because it scans each document. The solution mentioned here can be better if you need to find min/max of the indexed field: stackoverflow.com/a/6360583/3438640 Use find with sort and limit: db.

What is $$ root in MongoDB?

The $$ROOT variable contains the source documents for the group. If you'd like to just pass them through unmodified, you can do this by $pushing $$ROOT into the output from the group.


1 Answers

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

like image 150
Hossain Khademian Avatar answered Nov 09 '22 23:11

Hossain Khademian