如何更新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
}
}热门推荐
10 儿子立冬祝福语简短独特
11 对当兵的祝福语简短
12 侄儿高考试祝福语简短
13 伴郎红包祝福语朋友简短
14 媳妇生日简短祝福语朋友
15 公司年会祝福语简短最好
16 元旦感恩祝福语简短大全
17 红包祝福语简短10字
18 周六早晨祝福语简短