在 MongoDB 中使用 findOneAndUpdate () 进行更新?
findOneAndUpdate() 根据过滤和排序条件更新单个文档,即
db.collection.findOneAndUpdate(filter, update, options)
我们创建一个包含文档的集合 -
> db.demo328.insertOne({Name:"Chris",Marks:67});
{
"acknowledged" : true,
"insertedId" : ObjectId("5e516b19f8647eb59e56207a")
}
> db.demo328.insertOne({Name:"David",Marks:78});
{
"acknowledged" : true,
"insertedId" : ObjectId("5e516b24f8647eb59e56207b")
}
> db.demo328.insertOne({Name:"Bob",Marks:97});
{
"acknowledged" : true,
"insertedId" : ObjectId("5e516b2bf8647eb59e56207c")
}使用 find() 方法显示集合中的所有文档 -
> db.demo328.find();
这将生成以下输出 -
{ "_id" : ObjectId("5e516b19f8647eb59e56207a"), "Name" : "Chris", "Marks" : 67 }
{ "_id" : ObjectId("5e516b24f8647eb59e56207b"), "Name" : "David", "Marks" : 78 }
{ "_id" : ObjectId("5e516b2bf8647eb59e56207c"), "Name" : "Bob", "Marks" : 97 }以下是对 findOneAndUpdate() 进行更新的查询。这里我们增加特定文档的 Fields Marks -
> db.demo328.findOneAndUpdate({Name:"David"},{ $inc: { "Marks" : 10} });
{
"_id" : ObjectId("5e516b24f8647eb59e56207b"),
"Name" : "David",
"Marks" : 78
}使用 find() 方法显示集合中的所有文档 -
> db.demo328.find();
这将生成以下输出 -
{ "_id" : ObjectId("5e516b19f8647eb59e56207a"), "Name" : "Chris", "Marks" : 67 }
{ "_id" : ObjectId("5e516b24f8647eb59e56207b"), "Name" : "David", "Marks" : 88 }
{ "_id" : ObjectId("5e516b2bf8647eb59e56207c"), "Name" : "Bob", "Marks" : 97 }
广告
数据结构
网络
RDBMS
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
JavaScript
PHP