如何撤消mongoDB中文档的修改/更新?

时间:2015-04-29 11:01:44

标签: mongodb

我通过运行命令

错误地修改了集合中的文档
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 
    }
); 

它删除了我的第一个文档中的所有字段,但Persons集合中的_id字段除外。

以上命令导致了

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

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

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

所以我基本上想撤消修改。我该怎么做。?

1 个答案:

答案 0 :(得分:3)

你可以做的事情很少:

  
      
  1. 删除存储"分支":"计算机"的第一个条目,用:
  2.   
db.collection.remove({'_id': ObjectId("5527636be4b0b3959623d6f7")})
  
      
  1. 您可以删除整个集合,并使用以下内容重新开始:
  2.   
db.collection.remove({})

db.collection.drop()
  
      
  1. 即使如果您不想删除不正确的条目,也可以将其更新为:
  2.   
db.collection.update({'_id': ObjectId("5527636be4b0b3959623d6f7")}, {'name': 'Gaurav', 'country': 'India'})
  
      
  1. 如果您更新,只有指定的字段将被存储,其余的将被清除。因此,您必须使用$ set,如:
  2.   
db.collection.update({'_id': ObjectId("5527636be4b0b3959623d6f7")},{ $set: {'name': 'Gaurav', 'country': 'India'}},{upsert: true})

看,这有帮助。