Jimi
Jimi

Reputation: 1855

Get the document with the max value of a field in MongoDB

I'm using aggregation framework to get the max value of a field from a collection across a set of documents, like this

db.getCollection('Collection').aggregate([
   {$match: {"product": {$in: ["product-a"]}}},
   {$group: {_id: null, maxPrice: {$max: "$price"}}}
])

But what if I want to get the ID of the document that matches this criteria? How can I do that in the next stage of the pipeline?

Upvotes: 2

Views: 3615

Answers (1)

Ashh
Ashh

Reputation: 46491

You can put all the fields in $max operator like this... It will give you the document for the max field which is used at first in the $max object. Just I have used price here.

db.getCollection("Collection").aggregate([
  { "$match": { "product": { "$in": ["product-a"] } } },
  { "$group": {
    "_id": null,
    "maxPrice": {
      "$max": {
        "price": "$price",
        "_id": "$_id"
      }
    }
  }}
])

Upvotes: 3

Related Questions