MongoDb db.Collection.update() deleted my document

11,338

Solution 1

I use this syntax for updating multiple documents.

db.getCollection('YourDocument').update(
   { "matchingField" : "matchingValue"}, 
   { "$set": { "field": "value" } }, 
   { "multi": true } 
)

https://docs.mongodb.com/manual/tutorial/update-documents/

Solution 2

If you are trying to update only one field you should use the $set operator. But if what you want is to replace the document I had the same issue with Mongo and Meteor. I found in Mongo documentation that to replace the document you need not to use a $ operator and only pass field/value pairs:

The following operation passes an document that contains only field and value pairs. The document completely replaces the original document except for the _id field.

db.books.update({ item: "XYZ123" },
    {
     item: "XYZ123",
     stock: 10,
     info: { publisher: "2255", pages: 150 },
     tags: [ "baking", "cooking" ]
    })

https://docs.mongodb.com/manual/reference/method/db.collection.update/#example-update-replace-fields

But both in Robomongo and Meteor method this got the document removed.

The only way I found is to use the $set operator and replace every field. BUT this would try to update the mongo '_id', so I think is just a workaround...

db.books.update({ item: "XYZ123" },
    {
      $set: {
        item: "XYZ123",
        stock: 10,
        info: { publisher: "2255", pages: 150 },
        tags: [ "baking", "cooking" ]
      }
    })

What am I missing here? :/

Share:
11,338
Eddy
Author by

Eddy

Updated on June 22, 2022

Comments

  • Eddy
    Eddy almost 2 years

    I run an update statement on a mongodb database and it deleted my document! What did I do wrong?

    This is the update statement:

    db.Question.update( {Name: "IsSomeCompany"}, {ButtonValues: [0, 1, 2] } )
    

    I am using Robomongo and the reply was Updated 1 record(s) in 22ms but when I checked the database the record was gone. What am I missing here?

  • Paulo Oliveira
    Paulo Oliveira over 2 years
    For me this answer is a better help than the accepted one. @Ana Turrillo you took the time to explain the usage of $set whereas the first one is a small block code with a link to a larger document.