如何更新 MongoDB 数据库中的子对象?
要更新子对象,请在 MongoDB 中使用 $set。让我们先创建一个包含文档的集合 −
>db.demo21.insertOne({"StudentId":"STU-101","StudentDetails":{"StudentName":"Chris","StudentAge":21}});
{
"acknowledged" : true,
"insertedId" : ObjectId("5e14be8922d07d3b95082e6f")
}使用 find() 方法显示集合中的所有文档 −
> db.demo21.find().pretty();
这将产生以下输出 −
{
"_id" : ObjectId("5e14be8922d07d3b95082e6f"),
"StudentId" : "STU-101",
"StudentDetails" : {
"StudentName" : "Chris",
"StudentAge" : 21
}
}以下是更新 MongoDB 中子对象的查询 −
> db.demo21.update({"StudentId":'STU-101'},{$set:{'StudentDetails.StudentName':'Robert'}});
WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })使用 find() 方法显示集合中的所有文档 −
> db.demo21.find().pretty();
这将产生以下输出 −
{
"_id" : ObjectId("5e14be8922d07d3b95082e6f"),
"StudentId" : "STU-101",
"StudentDetails" : {
"StudentName" : "Robert",
"StudentAge" : 21
}
}
广告
数据结构
网络
RDBMS
操作系统
Java
iOS
HTML
CSS
Android
Python
C 语言编程
C++
C#
MongoDB
MySQL
Javascript
PHP