Reputation: 2421
I have the data
{"name" : "user1", age : 40 }
{"name" : "user2", age : 45 }
{"name" : "user3", age : 50 }
{"name" : "user4", age : 40 }
{"name" : "user5", age : 40 }
{"name" : "user6", age : 21 }
I want all rows having the maximum age.
Basically fetch all rows whose column value is maximum in the column.
SQL query : SELECT * FROM Person WHERE age = (SELECT max(age) FROM Person)
How can I do the same in MongoDB ? Thank you
Upvotes: 0
Views: 36
Reputation: 61273
You can do this with the aggregation framework like this:
db.collection.aggregate([
{ "$group": {
"_id": "$age",
"docs": { "$push": "$$ROOT" }
}},
{ "$sort": { "_id": -1 } },
{ "$limit": 1 }
])
Upvotes: 1