MongoDB 查询以更新索引 N 中的数组对象?
使用 MongoDB 中的 update() 更新数组对象。还需要使用点表示法。让我们使用文档创建一个集合 -
> db.demo489.insertOne(
... {
...
...
... details : [{
... id : 101,
... "Info1" : {
... "StudentName" : "Chris"
... },
... "Info2" : {
... "TeacherName" : "David"
... }
... },
... {
... id : 102,
... "Info1" : {
... "StudentName" : "Carol"
... },
... "Info2" : {
... "TeacherName" : "Mike"
... }
... }
...
... ]
... }
... );
{
"acknowledged" : true,
"insertedId" : ObjectId("5e8356e0b0f3fa88e22790ba")
}借助 find() 方法显示集合中的所有文档 -
> db.demo489.find();
这将产生以下输出 -
{ "_id" : ObjectId("5e8356e0b0f3fa88e22790ba"), "details" : [ { "id" : 101, "Info1" : {
"StudentName" : "Chris" }, "Info2" : { "TeacherName" : "David" } }, { "id" : 102, "Info1" : {
"StudentName" : "Carol" }, "Info2" : { "TeacherName" : "Mike" } } ] }以下是更新数组对象的查询 -
> db.demo489.update({"details.id":102},
... {$set: {"details.$.Info1.StudentName":"Robert",
... "details.$.Info2.TeacherName":"John",
... "details.$.CountryName" : "US"
...
... }
... })
WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })借助 find() 方法显示集合中的所有文档 -
> db.demo489.find().pretty();
这将产生以下输出 -
{
"_id" : ObjectId("5e8356e0b0f3fa88e22790ba"),
"details" : [
{
"id" : 101,
"Info1" : {
"StudentName" : "Chris"
},
"Info2" : {
"TeacherName" : "David"
}
},
{
"id" : 102,
"Info1" : {
"StudentName" : "Robert"
},
"Info2" : {
"TeacherName" : "John"
},
"CountryName" : "US"
}
]
}
广告
数据结构
网络
RDBMS
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP