0

Let's say I have a collection like this :

{_id: 1, value: 3, color: "white"}
{_id: 2, value: 5, color: "green"}
{_id: 3, value: 1, color: "white"}
{_id: 4, value: 2, color: "blue"}
{_id: 5, value: 4, color: "green"}

Is it possible to get the item with the highest value for each color ?

The expected output with our example would be :

{_id: 1, value: 3, color: "white"}
{_id: 2, value: 5, color: "green"}
{_id: 4, value: 2, color: "blue"}

The goal is to achieve this result in a single MongoDB request.

volent
  • 473
  • 6
  • 16
  • Possible duplicate of [MongoDB : Aggregation framework : Get last dated document per grouping ID](http://stackoverflow.com/questions/23360551/mongodb-aggregation-framework-get-last-dated-document-per-grouping-id) – Blakes Seven Mar 11 '16 at 22:58

2 Answers2

1

You can do it through aggregation as below

> db.collection.aggregate([
       {$sort: {'color': 1, value: -1}},
       {$group: {_id: '$color', value: {$first: '$value'}}}
 ]);
zangw
  • 43,869
  • 19
  • 177
  • 214
0

As a solution to group documents according to max value of color,you can perform aggregate operation utilizing $max operator

db.collection.aggregate([
{
      $group: {
      _id:{color:"$color"},
      value:{$max:"$value"}
      }
    }

  ]
);
Rubin Porwal
  • 3,736
  • 1
  • 23
  • 26
  • The goal was to get the whole items so this answer doesn't fit but thank you for the suggestion :) – volent Mar 11 '16 at 15:13