skip to Main Content

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


  1. Something simple like this can do the job:

    db.Employee.find({}).sort({Age:-1}).limit(2).forEach(function(doc){
    db.Employee.update({_id:doc._id},{$set:{Benefits:["Vacation","Rolex"]}})
    })
    
    Login or Signup to reply.
  2. 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:

        db.Employee.aggregate([
      {
        $sort: {
          Age: -1
        }
      },
      {
        $limit: 2
      },
      {
        $set: {
          Benefits: [
            "Vacation",
            "Rolex"
          ]
        }
      },
      {
        $merge: {
          into: "Employee",
          on: "_id",
          whenMatched: "replace",
        }
      }
    ])
    

    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

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search