在 MongoDB 中更新特定数组索引处对象?
要更新特定数组索引处的对象,请在 MongoDB 中使用 update()。我们先创建一个带有文档的集合 -
> db.updateObjectDemo.insertOne(
... {
... id : 101,
... "StudentDetails":
... [
... [
... {
... "StudentName": "John"
... },
... { "StudentName": "Chris" }
... ],
... [ { "StudentName": "Carol" },
... { "StudentName": "David" } ]
... ]
... }
... );
{
"acknowledged" : true,
"insertedId" : ObjectId("5ccdcd9b685b30d09a7111e0")
}以下是使用 find() 方法显示集合中所有文档的查询 -
> db.updateObjectDemo.find().pretty();
这将产生以下输出 -
{
"_id" : ObjectId("5ccdcd9b685b30d09a7111e0"),
"id" : 101,
"StudentDetails" : [
[
{
"StudentName" : "John"
},
{
"StudentName" : "Chris"
}
],
[
{
"StudentName" : "Carol"
},
{
"StudentName" : "David"
}
]
]
}以下是 MongoDB 中更新特定数组索引处的对象的查询 -
> db.updateObjectDemo.update({"id":101},{$set:{"StudentDetails.1.1.StudentName":"Mike"}});
WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })让我们检查一下特定索引 [1,1] 处的对象。值 “David” 已更新还是未更新 -
> db.updateObjectDemo.find().pretty();
这将产生以下输出 -
{
"_id" : ObjectId("5ccdcd9b685b30d09a7111e0"),
"id" : 101,
"StudentDetails" : [
[
{
"StudentName" : "John"
},
{
"StudentName" : "Chris"
}
],
[
{
"StudentName" : "Carol"
},
{
"StudentName" : "Mike"
}
]
]
}
广告
数据结构
网络
RDBMS
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP