我是mongoDB的新手,我陷入了一个简单的更新操作:
这是我存储的文件:
{
"_id" : "xyz",
"basicinfo_showcase_components" : {
"display_name" : "ritesh",
"display_email" : "xyz@gmail.comxsa",
"international_phone_number" : "+91 .....",
},
"address_components" : {
"country" : "India",
"postal_code" : "500004",
"state" : "Telangana",
"city" : "Hyderabad",
"subLocality1" : "aaaa",
"subLocality2" : "",
"subLocality3" : "",
"route" : "",
"geometry" : {
"lat" : 17.43143576387407,
"lng" : 78.464432457672046
},
"formatted_address" : "addrr"
}
}
现在我想更新上面文档中的address_components:
我试过了:
db.portfolio.update({ "_id" : "xyz", "$isolated" : "true" },
{
"address_components" : {
"country" : "Nepal",
"postal_code" : "878799",
"state" : "Telangana",
"city" : "Kathmandu",
"subLocality1" : "xyz",
"subLocality2" : "",
"subLocality3" : "",
"route" : "",
"geometry" : {
"lat" : 17.43143576387407,
"lng" : 78.464432457672046
},
"formatted_address" : "kath..."
}
});
但更新后,“basicinfo_showcase_components”将被删除。
即。更新的文档是:
{
"_id" : "ohris",
"address_components" : {
.......
}
}
你能指出错误吗?
答案 0 :(得分:1)
在您的更新查询中,您将整个文档作为更新文档传递,如果您只想更新文档的一个(或多个)字段,则应使用$set
运算符:
db.test.update({ "_id" : "xyz", "$isolated" : "true" },
{
$set : {
"address_components" : {
"country" : "Nepal",
"postal_code" : "878799",
"state" : "Telangana",
"city" : "Kathmandu",
"subLocality1" : "xyz",
"subLocality2" : "",
"subLocality3" : "",
"route" : "",
"geometry" : {
"lat" : 17.43143576387407,
"lng" : 78.464432457672046
},
"formatted_address" : "kath..."
}
}});