Reputation: 1261
Is it possible to update a document field based on another field using the update operator?
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
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
find()
and save()
PlayersSchema.find({ username: "moshe" }).forEach(function(doc){
doc.health = doc.maxHealth;
doc.save();
})
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