Asa*_*af 4 javascript mongoose mongodb
是否可以使用更新运算符根据另一个字段更新文档字段?
我有包含健康值和最大健康值的玩家集合,我的目标是将玩家健康值重置为最大健康值
db={
"players": [
{
"_id": ObjectId("5fba17c1c4566e57fafdcd7e"),
"username": "moshe",
"health": 0,
"maxHealth": 200,
}
]
}
// update
db.players.update({
username: "moshe"
},
{
"$set": {
"health": "$$maxHealth",
}
})
Run Code Online (Sandbox Code Playgroud)
谢谢!
从 MongoDB v4.2开始,您可以将更新与聚合管道一起使用,
PlayersSchema.update(
{ username: "moshe" },
[{
"$set": { "health": "$maxHealth" }
}]
)
Run Code Online (Sandbox Code Playgroud)
MongoDB v4.2 以下
find()
和save()
PlayersSchema.find({ username: "moshe" }).forEach(function(doc){
doc.health = doc.maxHealth;
doc.save();
})
Run Code Online (Sandbox Code Playgroud)
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);
});
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
5528 次 |
最近记录: |