我通过运行命令错误地修改了集合中的文档
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)
所以我基本上想撤消修改。我该怎么做。?
您可以做几件事:
- 删除存储“Branch”:“Computer”的第一个条目,其中:
db.collection.remove({'_id': ObjectId("5527636be4b0b3959623d6f7")})
Run Code Online (Sandbox Code Playgroud)
- 您可以删除整个集合并重新开始,方法是:
db.collection.remove({})
Run Code Online (Sandbox Code Playgroud)
或者
db.collection.drop()
Run Code Online (Sandbox Code Playgroud)
- 即使,如果您不想删除不正确的条目,也可以将其更新为:
db.collection.update({'_id': ObjectId("5527636be4b0b3959623d6f7")}, {'name': 'Gaurav', 'country': 'India'})
Run Code Online (Sandbox Code Playgroud)
- 如果更新,则仅存储指定的字段,其余字段将被清除。因此,您必须使用 $set,如下所示:
db.collection.update({'_id': ObjectId("5527636be4b0b3959623d6f7")},{ $set: {'name': 'Gaurav', 'country': 'India'}},{upsert: true})
Run Code Online (Sandbox Code Playgroud)
看,这有帮助。