I just want to update the top 2 highest fields in the database.
db.Employee.update({
db.Employee.find().sort({
Age: -1
}).limit(2) --This part here wont work--
},
{
$set: {
Benefits: ["Vacation", "Rolex"]
}
}
)
Apparently MongoDB does not support such ability.
How can I dynamically update the top 2 highest fields of my DB?
I do not want to resort to find the _id of the collection manually and then update the collection separately.
2
Answers
Something simple like this can do the job:
Starting in MongoDB 4.4, there is a
$merge
stage in the aggregation that can allow updating the same collection with the aggregation results, so you can do something like this:I tried it on my own db and it works, even though I could not make the playground update its own collection.
The documentation for the
$merge
can be found here