根据文档中的另一个字段更新字段

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)

谢谢!

tur*_*hal 5

从 MongoDB v4.2开始,您可以将更新与聚合管道一起使用,

PlayersSchema.update(
  { username: "moshe" },
  [{
    "$set": { "health": "$maxHealth" }
  }]
)
Run Code Online (Sandbox Code Playgroud)

MongoDB v4.2 以下

  1. 使用find()save()
PlayersSchema.find({ username: "moshe" }).forEach(function(doc){
  doc.health = doc.maxHealth; 
  doc.save();
})
Run Code Online (Sandbox Code Playgroud)
  1. 使用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)