Home > Blockchain >  How to use a field to update another field in MongoDB?
How to use a field to update another field in MongoDB?

Time:11-27

Here's an example of a document:

{
  _id: ObjectId("740b850f0406011059002b14"),
  product_id: 10,
  product_state: "available",
  old_state: null,
  ...
};

I'm trying to make an update where I store the value of the state in the field named 'old_state' and put the new value in the 'product_state' field. I want to apply this operation on multiple documents. So, how can I manage to make this operation? The result should be like:

{
  _id: ObjectId("740b850f0406011059002b14"),
  product_id: 10,
  product_state: "outOfStock",
  old_state: "available",
  ...
};

CodePudding user response:

You just have to reference the key name with $ prefix to the new key you want to update with

Note: This will work on MongoDB version >= 4.2

db.collection.update({
  product_id: 10,
}, [
{
  "$set": {
    "product_state": "outOfStock",
    "old_state": "$product_state"  // <-- Updates `old_state` key with the current value in `product_state` key
  }
}
])

Notice the $ prefix in product_state and the update block is enclosed in []

This will update the current value of product_state key to old_state key

Mongo Playground Sample Execution

CodePudding user response:

You need to use the newer array form of $update:

c = db.foo.update({_id:0}, [ {$addFields: {product_state: "new", os: "$product_state"}} ]);
  • Related