Asaf
Asaf

Reputation: 1261

Update field based on another field in the document

Is it possible to update a document field based on another field using the update operator?

See playground here

I have players collection with health and maxHealth, my goal is to reset the player health to the maxHealth value

db={
  "players": [
    {
      "_id": ObjectId("5fba17c1c4566e57fafdcd7e"),
      "username": "moshe",
      "health": 0,
      "maxHealth": 200,
      
    }
  ]
}

// update
db.players.update({
  username: "moshe"
},
{
  "$set": {
    "health": "$$maxHealth",
    
  }
})

Thanks!

Upvotes: 4

Views: 5969

Answers (1)

turivishal
turivishal

Reputation: 36094

You can use update with aggregation pipeline starting from MongoDB v4.2,

PlayersSchema.update(
  { username: "moshe" },
  [{
    "$set": { "health": "$maxHealth" }
  }]
)

Below MongoDB v4.2

  1. using find() and save()
PlayersSchema.find({ username: "moshe" }).forEach(function(doc){
  doc.health = doc.maxHealth; 
  doc.save();
})
  1. using find() and bulkWrite()
const players = await PlayersSchema.find({ username: "moshe" }, { maxHealth: 1 });
const updatePlayers = players.map(({ _id, maxHealth }) => ({
  updateOne: {
    filter: { _id: mongoose.Types.ObjectId(_id) },
    update: { health: maxHealth }
  }
}));
PlayersSchema.bulkWrite(updatePlayers).then(res => {
   console.log(res.insertedCount, res.modifiedCount, res.deletedCount);
});

Upvotes: 6

Related Questions