• Home
  • Jobs
  • coursesAndChallenges
  • Teachers
  • For business
  • Blog
  • ES/EN

0

25
Views
copying values inside a record from one key to other in mongodb

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?

11 days ago ·

Santiago Trujillo

1 answers
Answer question

0

You can do it with Aggregation framework:

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

Working example

11 days ago · Santiago Trujillo Report
Answer question
Remote jobs
Loading

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post job Plans Our process Startups
Legal
Terms and conditions Privacy policy
© 2022 PeakU Inc. All Rights Reserved.