是否可以使用update运算符基于另一个字段来更新文档字段?
我拥有健康和maxHealth的玩家集合,我的目标是将玩家健康重置为maxHealth值
db={
"players": [
{
"_id": ObjectId("5fba17c1c4566e57fafdcd7e"),
"username": "moshe",
"health": 0,
"maxHealth": 200,
}
]
}
// update
db.players.update({
username: "moshe"
},
{
"$set": {
"health": "$$maxHealth",
}
})
谢谢!
从MongoDB v4.2开始,您可以对聚合管道使用update,
PlayersSchema.update(
{ username: "moshe" },
[{
"$set": { "health": "$maxHealth" }
}]
)
在MongoDB v4.2以下
find()
和save()
PlayersSchema.find({ username: "moshe" }).forEach(function(doc){
doc.health = doc.maxHealth;
doc.save();
})
find()
和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);
});
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句