正在 MongoDB 更新完整的嵌入式文档

Updating complete embedded document in MongoDB

我是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" : {
   .......
  }
}

能否指出错误?

在您的更新查询中,您将整个文档作为更新文档传递,如果您只想更新一个(或多个)文档字段,您应该使用 $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..."
      }    
}});