0

I'm new to MongoDB. I'm trying to get a person's name who has max age. Here is a sample of my document:

    {
        "_id": ....
        "name": Alex,
        "age": 23,
        "city": NYC,
        "isActive": False
    }
    {
        "_id": .....
        "name": Kate,
        "age": 25,
        "city": SFO,
        "isActive": True
    }
    {
        "_id": .....
        "name": Dane,
        "age": 31,
        "city": SFO,
        "isActive": null
    }

Here is what I have tried so far

db.person.aggregate([{$group: {_id: {name: "$name", age: "$age"}}}, {$group: {_id: "", age: {$max: "$_id.age"}}}])

but I get only the age in the final output.

{ "_id" : "", "age" : 31 }

Is there a way to add the name is second pipe?

Junaid
  • 3,477
  • 1
  • 24
  • 24
  • This actually is not an aggregation at all. All you need do is sort the cursor and retrieve the top document `db.person.find().sort({ "age": -1 }).limit(1)`. Noting that [`$orderBy`](https://docs.mongodb.com/manual/reference/operator/meta/orderby/) in argument to `.findOne()` is deprecated now. – Neil Lunn Oct 19 '17 at 04:26
  • 1
    If you really must use aggregation then the same thing is `db.person.aggregate([{ "$sort": { "age": -1 } },{ "$limit": 1 }])`. Throw in a `$project` if you just want specific properties, or simply use projection with a standard `.find()` as is demonstrated. – Neil Lunn Oct 19 '17 at 04:30
  • I am trying to go with aggregate. Thanks for your second suggestion, `db.person.aggregate([{$group: {_id: {name: "$name", age: "$age"}}}, {$sort: {"_id.age": -1}}, {$limit: 1}])` worked for me – Junaid Oct 19 '17 at 09:34

0 Answers0