在MongoDB中更新许多文档
要更新许多文档,请使用UPSERT()和UPDATE()。让我们创建一个包含文档的集合-
> db.demo425.insertOne({"Name":"Chris","Age":21}); { "acknowledged" : true, "insertedId" : ObjectId("5e74ee4fbbc41e36cc3cae6c") } > db.demo425.insertOne({"Name":"David","Age":23}); { "acknowledged" : true, "insertedId" : ObjectId("5e74ee56bbc41e36cc3cae6d") } > db.demo425.insertOne({"Name":"Chris","Age":21}); { "acknowledged" : true, "insertedId" : ObjectId("5e74ee57bbc41e36cc3cae6e") } > db.demo425.insertOne({"Name":"Chris","Age":21}); { "acknowledged" : true, "insertedId" : ObjectId("5e74ee5cbbc41e36cc3cae6f") }
在find()方法的帮助下显示集合中的所有文档-
> db.demo425.find();
这将产生以下输出-
{ "_id" : ObjectId("5e74ee4fbbc41e36cc3cae6c"), "Name" : "Chris", "Age" : 21 } { "_id" : ObjectId("5e74ee56bbc41e36cc3cae6d"), "Name" : "David", "Age" : 23 } { "_id" : ObjectId("5e74ee57bbc41e36cc3cae6e"), "Name" : "Chris", "Age" : 21 } { "_id" : ObjectId("5e74ee5cbbc41e36cc3cae6f"), "Name" : "Chris", "Age" : 21 }
以下是在MongoDB中上载许多文档的查询-
> var b1 = db.demo425.initializeUnorderedBulkOp(); > b1.find( { Name: "Chris" } ).upsert().update( ... { ... $setOnInsert: { id:101}, ... $set: { Name: "Robert", Age:23 } ... } ... ); > b1.execute(); BulkWriteResult({ "writeErrors" : [ ], "writeConcernErrors" : [ ], "nInserted" : 0, "nUpserted" : 0, "nMatched" : 3, "nModified" : 3, "nRemoved" : 0, "upserted" : [ ] })
在find()方法的帮助下显示集合中的所有文档-
> db.demo425.find();
这将产生以下输出-
{ "_id" : ObjectId("5e74ee4fbbc41e36cc3cae6c"), "Name" : "Robert", "Age" : 23 } { "_id" : ObjectId("5e74ee56bbc41e36cc3cae6d"), "Name" : "David", "Age" : 23 } { "_id" : ObjectId("5e74ee57bbc41e36cc3cae6e"), "Name" : "Robert", "Age" : 23 } { "_id" : ObjectId("5e74ee5cbbc41e36cc3cae6f"), "Name" : "Robert", "Age" : 23 }