mongodb how to get max value from collections

Hossain Khademian picture Hossain Khademian · Aug 18, 2015 · Viewed 129.1k times · Source

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

Answer

Hossain Khademian picture Hossain Khademian · Aug 18, 2015

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