最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Update field based on another field in the document - Stack Overflow

programmeradmin1浏览0评论

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!

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!

Share Improve this question asked Jan 2, 2021 at 19:35 AsafAsaf 1,2592 gold badges16 silver badges19 bronze badges 2
  • use $maxHealth instead of $$maxHealth – Amir BenAmara Commented Jan 2, 2021 at 20:26
  • I've tried that, it's not working – Asaf Commented Jan 2, 2021 at 20:56
Add a ment  | 

1 Answer 1

Reset to default 6

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);
});
发布评论

评论列表(0)

  1. 暂无评论