MongoDB语法用于更新文档中数组内的对象?
为此,请findOneAndUpdate()在MongoDB中使用。该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
}
]
}