MongoDB - 更新所有匹配的嵌套文档

时间:2015-04-18 10:30:15

标签: mongodb nosql

我有这个MongoDB文档集。我想更新所有文件的PropertyContractors电话号码,其中包括" ContractorTelephone":" 0865215486"。

{
"_id": "4",
"PropertyType": "House",
"PropertyNameNumber": "49",
"PropertyStreet": "Paul Street",
"PropertyTown": "Farmleigh",
"PropertyCity": "Waterford City",
"PropertyCounty": "Co Waterford",
"PropertyBedrooms": "3",
"PropertyDescription": "Central, Cheap",
"PropertyFacilities": [
    {
        "FacilitiesSmoking": "Yes",
        "FacilitiesPets": "Yes",
        "FacilitiesBroadBand": "Yes",
        "FacilitiesTV": "Yes"
    }
],
"PropertyAvailable": "1",
"PropertyContractor": [
    {
        "ContractorName": "John Murphy",
        "ContractorTelephone": "0865215486",
        "ContractorType": "Plumber"
    }
]

}

我试过

db.Property.update(
{ PropertyContractor.ContractorTelephone: "0865215486" },
{
  $set: { PropertyContractor.ContractorTelephone: "0854854215" }
},
  { multi: true }
 )

但它只是说了。是错误的语法

提前致谢。

1 个答案:

答案 0 :(得分:0)

使用 $ positional operator ,它标识要更新的数组中的元素,而不显式指定数组中元素的位置:

db.Property.update(
    { 
       "PropertyContractor.ContractorTelephone": "0865215486" 
    },
    {
        "$set": {
           "PropertyContractor.$.ContractorTelephone": "0854854215" 
        }
    },
    { "multi": true }
 );