How do I get the whole document after $group and $max operation -Mongodb?

Viewed 39

Here's how my collection looks:

{"_id": 1, "price_history": [{date: 10-01-19, price: 10}, {date: 10-05-19, price: 15}...]...}
{"_id": 2, "price_history": [{date: 10-01-19, price: 12}, {date: 10-05-19, price: 14}...]...}
{"_id": 3, "price_history": [{date: 10-01-19, price: 17}, {date: 10-05-19, price: 25}...]...}
{"_id": 4, "price_history": [{date: 10-01-19, price: 10}, {date: 10-05-19, price: 16}...]...}

(The dates are all date objects, just wrote them this way to read easier)

So I'm able to get the max price from the "price_history" array, but I also want to get that date object that matches with that max price.

Here's what I have so far, I've removed a lot of irrelevant stuff to the question.

{
    $group: {
        '_id': 'stats', 
        'price_history_stats': {
            $push: {
                '_id': '$_id',
                'highest': {
                    $max: '$price_history.price'
                }
            }
        }
    }
}

The output I am getting is:

{
    '_id': 'stats',
    'price_history_stats': [
                {'_id': 1, 'highest': 15},
                {'_id': 1, 'highest': 14},
                {'_id': 1, 'highest': 25},
                {'_id': 1, 'highest': 16}
                ]
}

But I'm looking for a way to achieve this with the dates:

{
    '_id': 'stats',
    'price_history_stats': [
                {'_id': 1, 'highest': 15, date: 10-05-10},
                {'_id': 1, 'highest': 14, date: 10-05-10},
                {'_id': 1, 'highest': 25, date: 10-05-10},
                {'_id': 1, 'highest': 16, date: 10-05-10}
                ]
}

(Excuse any typos, I reformatted a lot of stuff for the question)

Any help would be appreciated. Thanks

1 Answers

If the intent is to find the max document for the group based on price, a combination of $sort first on price then $group with $last will produce a similar output.

Query: Link

db.collection.aggregate([
  {
    $unwind: "$price_history"
  },
  {
    $sort: {
      "price_history.price": 1
    }
  },
  {
    $group: {
      _id: "$_id",
      max_price_doc: {
        $last: "$price_history"
      }
    }
  }
]);

Output:(Demo)

[
  {
    "_id": 1,
    "max_price_doc": {
      "date": "10 - 05 - 19",
      "price": 15
    }
  },
  {
    "_id": 4,
    "max_price_doc": {
      "date": "10 - 05 - 19",
      "price": 16
    }
  },
  {
    "_id": 3,
    "max_price_doc": {
      "date": "10 - 05 - 19",
      "price": 25
    }
  },
  {
    "_id": 2,
    "max_price_doc": {
      "date": "10 - 05 - 19",
      "price": 14
    }
  }
]
Related