A.Fe
A.Fe

Reputation: 191

MongoDB 4.2.1 - updateMany: Error: the update operation document must contain atomic operators

So I have this issue with mongodb 4.2.1 using Robo 3T. I want to update specific documents, by moving a field inside another one which is an object.

Using update() like this works fine.

db.getCollection('myCollections').update(
    {
        randomId: ObjectId("......."),
    },
    [
        { $set: { "myObject.myField": "$myField" } },
        { $unset: [ "myField" ] }
    ])

But when I want to update all my documents using updateMany() like this.

db.getCollection('myCollections').updateMany(
    {
        randomId: ObjectId("......."),
    },
    [
        { $set: { "myObject.myField": "$myField" } },
        { $unset: [ "myField" ] }
    ])

I have an error

Failed to execute script.

Error: the update operation document must contain atomic operators 
Details:
DBCollection.prototype.updateMany@src/mongo/shell/crud_api.js:625:1
@(shell):1:1

I didn't try using the shell but I suppose it will tell me the same thing.

Edit

Example of a document before

{
  _id: ...,
  randomId: ObjectId(...),
  myField: 0.5
  myObject: {
    value1: 1,
    ...
  }
  ...
}

After

{
  _id: ...,
  randomId: ObjectId(...),
  myObject: {
    value1: 1,
    myField: 0.5,
    ...
  }
  ...
}

Upvotes: 11

Views: 9708

Answers (4)

adi
adi

Reputation: 1130

This is to help people who did the same mistake of leaving $set like me.

So it gave me the same error message specified in the question.

Append $set as well in the query.

Before:

db.myData.updateOne({key:"value"},{key:"new-value"})

After:

db.myData.updateOne({key:"value"},{$set:{key:"new-value"}}) 

Then I was able to update my data.

Upvotes: 2

prasad_
prasad_

Reputation: 14317

Update the document using $rename update operator; it is just renaming the field.

db.upd.updateOne(
  { randomId: ObjectId("xyz")},
  { $rename: { myField: "myObject.myField" } }
}

Upvotes: 2

A.Fe
A.Fe

Reputation: 191

My bad. I just tried with mongo shell and it works fine. Should stop using robo 3T for update.

Sorry for the bother and thanks for the answers

Upvotes: 8

Matheus Hatje
Matheus Hatje

Reputation: 987

The second parameter of updateOne() and updateMany() must by an Object, so basically you are using a wrong syntax, try like this instead:

db.getCollection('myCollections').updateMany({
    randomId: ObjectId("......."),
}, {
    $set: {
        "myObject.myField": "$myField"
    },
    $unset: {
        "myField": 1
    }
})

Upvotes: -1

Related Questions