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
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.
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.
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With