如何在MongoDB中更新子对象?
要更新子对象,请使用$set运算符。让我们首先用文档创建一个集合-
>db.updateChildObjectsDemo.insertOne({"StudentName":"Chris","StudentOtherDetails":{"StudentSubject":"MongoDB","StudentCountryName":"AUS"}});
{
"acknowledged" : true,
"insertedId" : ObjectId("5ce964e078f00858fb12e91f")
}以下是在find()方法的帮助下显示集合中所有文档的查询-
> db.updateChildObjectsDemo.find().pretty();
这将产生以下输出-
{
"_id" : ObjectId("5ce964e078f00858fb12e91f"),
"StudentName" : "Chris",
"StudentOtherDetails" : {
"StudentSubject" : "MongoDB",
"StudentCountryName" : "AUS"
}
}以下是更新MongoDB中子对象的查询-
> db.updateChildObjectsDemo.update({"StudentName" : "Chris"},{$set:{"StudentOtherDetails.StudentCountryName":"UK"}});
WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })让我们再次检查文档-
> db.updateChildObjectsDemo.find().pretty();
这将产生以下输出-
{
"_id" : ObjectId("5ce964e078f00858fb12e91f"),
"StudentName" : "Chris",
"StudentOtherDetails" : {
"StudentSubject" : "MongoDB",
"StudentCountryName" : "UK"
}
}热门推荐
10 儿子立冬祝福语简短独特
11 对当兵的祝福语简短
12 侄儿高考试祝福语简短
13 伴郎红包祝福语朋友简短
14 媳妇生日简短祝福语朋友
15 公司年会祝福语简短最好
16 元旦感恩祝福语简短大全
17 红包祝福语简短10字
18 周六早晨祝福语简短