Home > database >  copying values inside a record from one key to other in mongodb
copying values inside a record from one key to other in mongodb

Time:03-04

I am working on MongoDB. I am trying to append some new key-value pairs to my existing collection. I got more than 50 documents in my collection, in all of which I want to update a new key value pair. In the new key value pair I am adding, one of the values of the key should be from one of the existing key value pair of the same collection. For example:

{ name : "algebra", quantity : 25 }

Now I want to update each of the document with

{ category : "maths" , available_quantity : 25 }

Without entering distinctly for every document its available quantity. I want it to be picked from it's respective quantity's value, and be inserted in the new key available_quantity. I am using the code to update the document :

db.books.update( {} , { $set : { category : "maths" , available_quantity : `__ ? __` }, false, true }

What best can I put in __ ? __ block?

CodePudding user response:

You can do it with Aggregation framework:

db.books.update({},
[
  {
    "$set": {
      "available_quantity": "$quantity"
    }
  }
],
{
  multi: true
})

Working example

  • Related