YulePale
YulePale

Reputation: 7736

MongoDB aggregation: How to get an object in an array that has the highest value and also satisfies another condition without using $reduce?

This question is a continuation from this question.

Let's say I have this data

[
    {id:0, points:-9, rank:true}
    {id:1, points:-49, rank:true}
    {id:2, points:9, rank:false}
    {id:3, points:-24, rank:false}
    {id:4, points:3, rank:true}
]

I want to get the object with the highest points and rank is equal to positive and add the property winner:true So in this case the object with id:4. How can I achieve the same in MongoDB aggregation without using $reduce?

Upvotes: 1

Views: 37

Answers (1)

turivishal
turivishal

Reputation: 36134

You can try,

  • $match rank is positive
  • $sort by points ascending order
  • $group by null and get last object from group document
  • $replaceRoot to replace winner object to root
  • $addFields to add new field winner: true
db.collection.aggregate([
  { $match: { rank: true } },
  { $sort: { points: 1 } },
  {
    $group: {
      _id: null,
      winner: { $last: "$$ROOT" }
    }
  },
  { $replaceRoot: { newRoot: "$winner" } },
  { $addFields: { winner: true } }
])

Playground

Upvotes: 2

Related Questions