问题
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
bypoints
ascending order$group
by null and get last object from group document$replaceRoot
to replacewinner
object to root$addFields
to add new fieldwinner: 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