Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to undo modification/update on document in mongoDB?

Tags:

mongodb

I have mistakenly modified document in collection by running the command

db.getCollection('Persons').update(
    // query 
    {

    },

    // update 
    {
       "Branch":"computer"
    },

    // options 
    {
        "multi" : false,  // update only one document 
        "upsert" : false  // insert a new document, if no existing document match the query 
    }
); 

It had removed all fields in my first document except _id field in Persons collection.

The above command has resulted in

/* 1 */
{
    "_id" : ObjectId("5527636be4b0b3959623d6f7"),
    "Branch" : "computer"
}

/* 2 */
{
    "_id" : ObjectId("5527637ee4b0b3959623d6f8"),
    "name" : "rajnish",
    "country" : "Bhutan"
}

/* 3 */
{
    "_id" : ObjectId("552d133b44aef0215235e3e9"),
    "name" : "amol",
    "country" : "india"
}

so I basically wanted to undo modification. How do I do it.?

like image 665
chetan Avatar asked Oct 31 '22 05:10

chetan


1 Answers

There are few things, which you can do:

  1. Delete that first entry which stores "Branch": "Computer", with:
db.collection.remove({'_id': ObjectId("5527636be4b0b3959623d6f7")})
  1. You can delete the whole collection, and start fresh, with:
db.collection.remove({})

OR

db.collection.drop()
  1. Even, if you don't want to delete the incorrect entry, you can update it as:
db.collection.update({'_id': ObjectId("5527636be4b0b3959623d6f7")}, {'name': 'Gaurav', 'country': 'India'})
  1. If you update, only the fields specified will be store and rest will be cleared out. So, you have to use $set as in:
db.collection.update({'_id': ObjectId("5527636be4b0b3959623d6f7")},{ $set: {'name': 'Gaurav', 'country': 'India'}},{upsert: true})

See, that helps.

like image 198
Gaurav Dave Avatar answered Nov 15 '22 05:11

Gaurav Dave