使用 FindAndUpdate() 更新数组的 MongoDB 查询?
要更新数组,请改用 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 }
广告
数据结构
网络
RDBMS
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP