MongoDB 语法如何更新文档中数组中的对象?
为此,在 MongoDB 中使用 findOneAndUpdate()。findOneAndUpdate() 方法会根据筛选和排序条件更新单个文档。
让我们创建一个包含文档的集合 −
> db.demo553.insertOne(
... {
... id:101,
... "Name":"John",
... midExamDetails:
... [
... {"SubjectName":"MySQL","Marks":70},
... {"SubjectName":"MongoDB","Marks":35}
... ]
... }
... );
{
"acknowledged" : true,
"insertedId" : ObjectId("5e8e3da19e5f92834d7f05ed")
}使用 find() 方法显示集合中的所有文档 −
> db.demo553.find();
这将产生以下输出 −
{ "_id" : ObjectId("5e8e3da19e5f92834d7f05ed"), "id" : 101, "Name" : "John", "midExamDetails" : [
{ "SubjectName" : "MySQL", "Marks" : 70 },
{ "SubjectName" : "MongoDB", "Marks" : 35 }
] }以下是对 MongoDB 文档中数组中对象进行更新的语法的查询 −
> db.demo553.findOneAndUpdate(
... { id:101,
... "midExamDetails.SubjectName":"MongoDB"
... },
... { $set:{
... 'midExamDetails.$.Marks': 97
... }
... }
... );
{
"_id" : ObjectId("5e8e3da19e5f92834d7f05ed"),
"id" : 101,
"Name" : "John",
"midExamDetails" : [
{
"SubjectName" : "MySQL",
"Marks" : 70
},
{
"SubjectName" : "MongoDB",
"Marks" : 35
}
]
}使用 find() 方法显示集合中的所有文档 −
> db.demo553.find().pretty();
这将产生以下输出 −
{
"_id" : ObjectId("5e8e3da19e5f92834d7f05ed"),
"id" : 101,
"Name" : "John",
"midExamDetails" : [
{
"SubjectName" : "MySQL",
"Marks" : 70
},
{
"SubjectName" : "MongoDB",
"Marks" : 97
}
]
}
广告
数据结构
网络
RDBMS
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP