Search code examples
mongodbmonk

How to override the document in MongoDB


I have mongodb collection with below document

{
    "_id" : ObjectId("5652f7e1a9fddf438369c866"),
    "USER_ID" : "Vinsy",
    "USER_NAME" : "Vinsy",
    "FIRST_NAME" : "XYZxx",
    "LAST_NAME" : "ABC",
    "CONTACTS"  :[]
}

I am trying to update the document with below query

collection.update({
        USER_ID: req.body.USER_ID
    },{
        "USER_ID" : "Vinsy",
        "USER_NAME" : "Vinsy",
        "FIRST_NAME" : "XYZxx",
        "LAST_NAME" : "ABC",
    }, function(error, data) {

        try {
            if (data) {
                res.json("SUCCESS");
            } else {
                res.json("FAILURE" + error);
            }
        } catch (e) {
            res.json("FAILURE" + e);
        }
    });

The query is updating the document but it's removing CONTACTS. How to keep it as it is? really appreciate you help.


Solution

  • You need to specify the $set operator. The $set operator instructs MongoDB that you want to update specific fields in a document rather than overwriting it with a new document.

    collection.update({
            USER_ID: req.body.USER_ID
       },
       { $set:
         {
           "USER_ID" : "Vinsy",
           "USER_NAME" : "Vinsy",
           "FIRST_NAME" : "XYZxx",
           "LAST_NAME" : "ABC",
         }
       }