skip to Main Content

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.

2

Answers


  1. As per this comment:

    I just want to get rid of the original array completely. I don’t use the original value.

    In that case, don’t use the pipeline syntax for update. So you only need to remove the [...] surrounding $set:

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

    And if you do need an update pipeline for some other steps, then unset key before setting a new value:

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

    Mongo Playground

    Login or Signup to reply.
  2. Use $literal

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

    Mongo Playground

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search