0

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

1

1 Answer 1

1

You can do this with the aggregation framework like this:

db.collection.aggregate([
    { "$group": { 
        "_id": "$age", 
        "docs": { "$push": "$$ROOT" } 
    }},
    { "$sort": { "_id": -1 } },
    { "$limit": 1 }
])
Sign up to request clarification or add additional context in comments.

2 Comments

Thank you for your response. Can you explain what you are doing there ?
@sujithvm Please read my other answer here for more details.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.