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

che*_*tan 5 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 
    }
); 
Run Code Online (Sandbox Code Playgroud)

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

上面的命令导致

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

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

/* 3 */
{
    "_id" : ObjectId("552d133b44aef0215235e3e9"),
    "name" : "amol",
    "country" : "india"
}
Run Code Online (Sandbox Code Playgroud)

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

Gau*_*ave 2

您可以做几件事:

  1. 删除存储“Branch”:“Computer”的第一个条目,其中:
db.collection.remove({'_id': ObjectId("5527636be4b0b3959623d6f7")})
Run Code Online (Sandbox Code Playgroud)
  1. 您可以删除整个集合并重新开始,方法是:
db.collection.remove({})
Run Code Online (Sandbox Code Playgroud)

或者

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

看,这有帮助。

  • 这不是您提供的可行解决方案。顺便说一句,感谢您的努力。 (3认同)
  • 不,你无法撤消,但我的第 4 点基本上告诉你更新功能可以做什么,以及如何采取预防措施。另一件事是,如果您有大型数据库并且它是活动的,那么最好进行备份,这样如果您搞砸了事情,您可以使用最近的备份进行恢复。那。将是可行的。 (2认同)