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

放肆的年华 提交于 2020-12-13 21:00:50

问题


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?


回答1:


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



来源:https://stackoverflow.com/questions/65039780/mongodb-aggregation-how-to-get-an-object-in-an-array-that-has-the-highest-value

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!