MongoDB查询以使用FindAndUpdate()更新数组?
要更新数组,请在MongoDB中使用findAndModify()。让我们创建一个包含文档的集合-
> db.demo152.insertOne({"id":102,"Name":["Chris","David"],Score:45}); { "acknowledged" : true, "insertedId" : ObjectId("5e3515bcfdf09dd6d08539dd") } > db.demo152.insertOne({"id":103,"Name":["Mike","Carol"],Score:65}); { "acknowledged" : true, "insertedId" : ObjectId("5e3515cafdf09dd6d08539de") }
在find()方法的帮助下显示集合中的所有文档-
> db.demo152.find();
这将产生以下输出-
{ "_id" : ObjectId("5e3515bcfdf09dd6d08539dd"), "id" : 102, "Name" : [ "Chris", "David" ], "Score" : 45 } { "_id" : ObjectId("5e3515cafdf09dd6d08539de"), "id" : 103, "Name" : [ "Mike", "Carol" ], "Score" : 65 }
以下是更新数组的查询-
> var d = db.demo152.findAndModify({ ... query: { ... id:102, ... Score: {$lt:50}, ... Name: "Chris" ... }, ... update: { ... $set : {"Name.$": "Robert"}, ... $inc: {Score: 20 } ... } ... } ... ... )
在find()方法的帮助下显示集合中的所有文档-
> db.demo152.find();
这将产生以下输出-
{ "_id" : ObjectId("5e3515bcfdf09dd6d08539dd"), "id" : 102, "Name" : [ "Robert", "David" ], "Score" : 65 } { "_id" : ObjectId("5e3515cafdf09dd6d08539de"), "id" : 103, "Name" : [ "Mike", "Carol" ], "Score" : 65 }