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

MongoDB – Overwrite the whole array field instead of its item

I have this schema:{ key: [] }. I want to convert it to { key: { foo: number } }.

This is the query I came up with:

db.collection.update({}, [
  {
    "$set": {
      key: { foo: 43 }
    }
  }
], { multi: true })

However, it updates the individual array item instead of the array as a whole. I.e. the document:

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

{ key: [1, 2] }

becomes :

{ key: [ { foo: 43 }, { foo: 43 } ] }

instead of:

{ key: { foo: 43 } }.

I just want to get rid of the original array completely. I can just remove the field, then write the update. But is there a way to do it in one fell swoop?

Update: I have to use the pipeline, there’re other stuff going on.

>Solution :

Use $literal

db.collection.update({},
[
  {
    "$set": {
      "key": {
        "$literal": {
          "foo": 43
        }
      }
    }
  }
])

Mongo Playground

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