如何在嵌套的mongo文档中更新属性

时间:2015-08-04 15:26:48

标签: mongodb mongodb-query

我想更新嵌套的mongo文档中的特定属性

{
    "_id" : ObjectId("55af76e60b0e4b318ba822ec"),
    "make" : "MERCEDES-BENZ",
    "model" : "E-CLASS",
    "variant" : "E 250 CDI CLASSIC",
    "fuel" : "Diesel",
    "cc" : 2143,
    "seatingCapacity" : 5,
    "variant_+_fuel" : "E 250 CDI CLASSIC (Diesel)",
    "make_+_model_+_variant_+_fuel" : "MERCEDES-BENZ E-CLASS E 250 CDI CLASSIC (Diesel)",
    "dropdown_display" : "E-CLASS E 250 CDI CLASSIC (Diesel)",
    "vehicleSegment" : "HIGH END CARS",
    "abc" : {
        "variantId" : 1000815,
        "makeId" : 1000016,
        "modelId" : 1000556,
        "fuelId" : 2,
        "segmentId" : 1000002,
        "price" : 4020000
    },
    "def" : {
        "bodyType" : 1,
        "makeId" : 87,
        "modelId" : 21584,
        "fuel" : "DIESEL",
        "vehicleSegmentType" : "E2"
    },
    "isActive" : false
}

这是我的文件。如果我想在"nonPreferred"内添加或更新密钥"abc"的值,我该如何处理呢?

我尝试了这个查询:

db.FourWheelerMaster.update(
    { "abc.modelId": 1000556 }, 
    {
        $Set: {
            "abc": {
                "nonPreferred": ["Mumbai", "Pune"]
            }
        }
    }, 
    {multi:true}
)

但它会更新整个"abc"结构,删除其中的所有键:值,并仅保留新插入的键值,如下所示

"abc" : {
    "nonPreferred" : [
        "Mumbai",
        "Pune"
    ]
},

有人能告诉我如何更新其中的特定属性而不是所有完整的密钥吗?

1 个答案:

答案 0 :(得分:0)

您需要使用 $set 运算符以及 {{而不是 $push 运算符。 3}} 修饰符分别附加值的每个元素,如下所示:

db.FourWheelerMaster.update(
    { "abc.modelId": 1000556 }, 
    {
        "$push": {
            "abc.nonPreferred": {
                "$each": ["Mumbai", "Pune"]  
            }          
        }
    }, 
    { "multi": true }
)