Wolf
Wolf

Reputation: 337

MongoDB: group, then retrieve entry with max value for each group

In the collection below, I'd like to group by author, and then, for each author, show the name of the entry with the highest price.

[
  { "name": "Design", "price": 499, "author": "ted" },
  { "name": "Launch", "price": 999, "author": "ted" },
  { "name": "Test",  "price": 1200, "author": "bob" },
  { "name": "Scale",  "price": 1499, "author": "bob" }
]

So, here my query should return Launch and Scale.

I've tried aggregating as follows, but I'm not sure what to do afterwards, short of pulling all entries onto the client and then processing all the groups to find the entry with the max price (which sounds very inefficient).

[
  {
    "$group": {
       "_id": "$author",
       "entry": {
         "$push": {
           "price": "$price",
           "name": "$name"
         }
       }
    }
  }
]

What's an efficient way to do this?

Thanks!

Upvotes: 1

Views: 38

Answers (1)

Boris Hafei
Boris Hafei

Reputation: 46

as per the answer from MongoDB - get documents with max attribute per group in a collection

please have a try

db.collection.aggregate([
    { "$sort": {  "price": -1 } },
    { "$group": {
        "_id": "$author",
        "price": { "$first": "$price" },
        "name": { "$first" "$name" }
    }}
])

Upvotes: 1

Related Questions