Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to use $getField in update MongoDB

I have a simple mongoDB document:

{
  _id: ObjectId("5c8eccc1caa187d17ca6ed16"),
  city: 'ALPINE',
  zip: '35014',
  loc: { y: 33.331165, x: 86.208934 },
  pop: 3062,
  state: 'AL'
}

The only thing I want to do is to add a new property population and set it with a value from pop property.

I’ve tried to use $getField like this: updateOne({}, {$set: {"population": { $getField: "pop" }}}). But the result is too straightforward xD

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

{
  _id: ObjectId("5c8eccc1caa187d17ca6ed16"),
  city: 'ALPINE',
  zip: '35014',
  loc: { y: 33.331165, x: 86.208934 },
  pop: 3062,
  state: 'AL',
  population: { '$getField': 'pop' }
}

So how can I set population field to value from pop field?

>Solution :

You can do like this, without $getField:

db.collection.update({},
[
  {
    $set: {
      "population": "$pop"
    }
  }
])

Here’s the working link.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading