我需要使用nodejs 更新 mongodb中的嵌套数组。我试过像this但没有帮助,甚至没有抛出错误。
我的收藏是
{
"country_details": [
{
"cities": [
"Abbeville"
],
"_id": "5a6ec189bb68bb09105eabe8",
"countryCode": "US",
"countryName": "United States"
}
],
"deletion_indicator": "N",
"_id": "5a6ec189bb68bb09105eabe7",
"date_created": "Mon Jan 29 2018 12:09:05 GMT+0530 (India Standard Time)",
"__v": 0
}
我希望更新城市,我尝试过一次
let query = {_id: "5a6ec189bb68bb09105eabe7", countryCode: "US", countryName: "United States"};
countryAndCitiesModel.collection.update(
query,
{$push: {"country_details.$.cities": "ABC"}},
(err, result)=> {
if(err){
return next(err);
}else{
return next(result);
}
});
没有获得更新,但获得结果就像是
{
"ok": 1,
"nModified": 0,
"n": 0
}
请帮忙..谢谢
答案 0 :(得分:2)
您尝试匹配countryCode
和countryName
这些是嵌套对象country_details
的属性,这就是您的查询无法与任何文档匹配的原因。要解决此问题,您应该修复字段的路径:
db.collection.update(
{_id: "5a6ec189bb68bb09105eabe7", "country_details.countryCode": "US", "country_details.countryName": "United States"},
{$push: {"country_details.$.cities": "ABC"}})