要更新部分文档数量,请将multi设置为true。让我们创建一个包含文档的集合-
> db.demo312.insertOne({"FirstName":"Robert"}); { "acknowledged" : true, "insertedId" : ObjectId("5e50ce16f8647eb59e56204a") } > db.demo312.insertOne({"FirstName":"Bob"}); { "acknowledged" : true, "insertedId" : ObjectId("5e50ce19f8647eb59e56204b") } > db.demo312.insertOne({"FirstName":"Robert"}); { "acknowledged" : true, "insertedId" : ObjectId("5e50ce1cf8647eb59e56204c") } > db.demo312.insertOne({"FirstName":"David"}); { "acknowledged" : true, "insertedId" : ObjectId("5e50ce20f8647eb59e56204d") } > db.demo312.insertOne({"FirstName":"Robert"}); { "acknowledged" : true, "insertedId" : ObjectId("5e50ce22f8647eb59e56204e") }
在find()
方法的帮助下显示集合中的所有文档-
> db.demo312.find();
这将产生以下输出-
{ "_id" : ObjectId("5e50ce16f8647eb59e56204a"), "FirstName" : "Robert" } { "_id" : ObjectId("5e50ce19f8647eb59e56204b"), "FirstName" : "Bob" } { "_id" : ObjectId("5e50ce1cf8647eb59e56204c"), "FirstName" : "Robert" } { "_id" : ObjectId("5e50ce20f8647eb59e56204d"), "FirstName" : "David" } { "_id" : ObjectId("5e50ce22f8647eb59e56204e"), "FirstName" : "Robert" }
以下是更新部分文档的查询
> db.demo312.update({"FirstName":"Robert"},{$set:{"FirstName":"Sam"}},{multi:true}); WriteResult({ "nMatched" : 3, "nUpserted" : 0, "nModified" : 3 })
在find()
方法的帮助下显示集合中的所有文档-
> db.demo312.find();
这将产生以下输出-
{ "_id" : ObjectId("5e50ce16f8647eb59e56204a"), "FirstName" : "Sam" } { "_id" : ObjectId("5e50ce19f8647eb59e56204b"), "FirstName" : "Bob" } { "_id" : ObjectId("5e50ce1cf8647eb59e56204c"), "FirstName" : "Sam" } { "_id" : ObjectId("5e50ce20f8647eb59e56204d"), "FirstName" : "David" } { "_id" : ObjectId("5e50ce22f8647eb59e56204e"), "FirstName" : "Sam" }