mongodbmongodb-queryaggregation-framework

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:

{ 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