Replacement Operation using Update Command

I’m trying to figure out of we can still replace document using update command on mongo shell 5.0, documentation says we can and even following the exact example provided in it doesn’t work and gives following error:

MongoInvalidArgumentError: Update document requires atomic operators

Test Data:

db.books.insertMany([
  {
    "_id" : 1,
    "item" : "TBD",
    "stock" : 0,
    "info" : { "publisher" : "1111", "pages" : 430 },
    "tags" : [ "technology", "computer" ],
    "ratings" : [ { "by" : "ijk", "rating" : 4 }, { "by" : "lmn", "rating" : 5 } ],
    "reorder" : false
   },
   {
    "_id" : 2,
    "item" : "XYZ123",
    "stock" : 15,
    "info" : { "publisher" : "5555", "pages" : 150 },
    "tags" : [ ],
    "ratings" : [ { "by" : "xyz", "rating" : 5 } ],
    "reorder" : false
   }
]);

Update command to replace:

db.books.update({ item: 'ZZZ135' },{ item: 'ZZZ135',stock: 5,tags: [ 'database' ]},{ upsert: true } )

Hi @Osaf_Khalid,

Just to clarify, are you utilising mongosh and not mongo shell?

mongosh typically follows the syntax of the older mongo shell but this is not always the case.

MongoInvalidArgumentError: Update document requires atomic operators

The updateOne documentation states that the “update document” must contain only update operator expression(s) of which $set is one. The update command you’ve provided does not contain the update operator expression which is causing the error you’ve provided.

Please also note that update() is deprecated and you should instead use updateOne() or updateMany() if you are using mongosh.

You can test the below example with the $set update operator expression:

db.books.updateOne({ item: "ZZZ135" },{$set:{ item: "ZZZ135",stock: 5,tags: [ "database" ]}},{ upsert: true } )

If you expect to provide just a document with any update operator expressions, you should be using db.collection.replaceOne instead.

Let me know if the above helps and/or if it answers your question. If not, please advise the outcome you are expecting when running the command.

Regards,
Jason

This topic was automatically closed 5 days after the last reply. New replies are no longer allowed.