最快的方法是replaceOne()
在MongoDB中使用。让我们创建一个包含文档的集合-
> db.demo431.insertOne({"Name":"Chris","Age":32}); { "acknowledged" : true, "insertedId" : ObjectId("5e770ba6bbc41e36cc3cae89") } > db.demo431.insertOne({"Name":"David","Age":31}); { "acknowledged" : true, "insertedId" : ObjectId("5e770bacbbc41e36cc3cae8a") } > db.demo431.insertOne({"Name":"John","Age":24}); { "acknowledged" : true, "insertedId" : ObjectId("5e770bb3bbc41e36cc3cae8b") } > db.demo431.insertOne({"Name":"Bob","Age":22}); { "acknowledged" : true, "insertedId" : ObjectId("5e770bb8bbc41e36cc3cae8c") }
在find()
方法的帮助下显示集合中的所有文档-
> db.demo431.find();
这将产生以下输出-
{ "_id" : ObjectId("5e770ba6bbc41e36cc3cae89"), "Name" : "Chris", "Age" : 32 } { "_id" : ObjectId("5e770bacbbc41e36cc3cae8a"), "Name" : "David", "Age" : 31 } { "_id" : ObjectId("5e770bb3bbc41e36cc3cae8b"), "Name" : "John", "Age" : 24 } { "_id" : ObjectId("5e770bb8bbc41e36cc3cae8c"), "Name" : "Bob", "Age" : 22 }
以下是更新MongoDB中整个文档(所有字段)的查询-
> db.demo431.replaceOne( ... { "Name" : "John" }, ... { "Name" : "Robert", "Age" :45 } ... ); { "acknowledged" : true, "matchedCount" : 1, "modifiedCount" : 1 }
在find()
方法的帮助下显示集合中的所有文档-
> db.demo431.find();
这将产生以下输出-
{ "_id" : ObjectId("5e770ba6bbc41e36cc3cae89"), "Name" : "Chris", "Age" : 32 } { "_id" : ObjectId("5e770bacbbc41e36cc3cae8a"), "Name" : "David", "Age" : 31 } { "_id" : ObjectId("5e770bb3bbc41e36cc3cae8b"), "Name" : "Robert", "Age" : 45 } { "_id" : ObjectId("5e770bb8bbc41e36cc3cae8c"), "Name" : "Bob", "Age" : 22 }