使用公式更新集合中文件的每个字段的 MongoDB 查询?
若要使用公式更新集合中文件的每个字段,请使用 MongoDB update()。我们创建一个包含以下文档的集合:
> db.demo749.insertOne({"details":[{"id":1,a:10},{"id":2,a:5},{"id":3,a:20}]});
{
"acknowledged" : true,
"insertedId" : ObjectId("5eae6fb0a930c785c834e565")
}使用 find() 方法显示集合中的所有文档:
> db.demo749.find().pretty();
这将生成以下输出:
{
"_id" : ObjectId("5eae6fb0a930c785c834e565"),
"details" : [
{
"id" : 1,
"a" : 10
},
{
"id" : 2,
"a" : 5
},
{
"id" : 3,
"a" : 20
}
]
}以下是使用公式更新集合中文件的每个字段的查询:
> db.demo749.update(
... {
...
... },
... {
... $mul: { "details.$[].a": 2/5}
... },
... { multi:true}
... )
WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })使用 find() 方法显示集合中的所有文档:
> db.demo749.find().pretty();
这将生成以下输出:
{
"_id" : ObjectId("5eae6fb0a930c785c834e565"),
"details" : [
{
"id" : 1,
"a" : 4
},
{
"id" : 2,
"a" : 2
},
{
"id" : 3,
"a" : 8
}
]
}
广告
数据结构
网络
RDBMS
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP