更新数组中嵌套多个级别的文档

时间:2019-09-05 16:43:30

标签: arrays mongodb mongodb-query

我在MongoDb中具有此JSON结构,并且想要更新更改嵌套数组中特定项目的特定值。我想将键 targetAreaId USER_MESSAGE 更改为 VISUAL_MESSAGE

{
"_id" : "5cde9f482f2d5b924f492da2",
"scenario" : "SCENARIOX",
"mediaType" : "VISUAL",
"opCon" : "NORMAL",
"stepConfigs" : [ 
    {
        "stepType" : "STEPX",
        "enabled" : true,
        "configs" : [ 
            {
                "contentTemplateId" : "5cde9f472f2d5b924f492973",
                "scope" : "STANDARD",
                "key" : "CONTENT"
            }, 
            {
                "priorityId" : "5cde9f472f2d5b924f49224f",
                "scope" : "STANDARD",
                "key" : "PRIORITY"
            }, 
            {
                "targetAreaId" : "USER_MESSAGE",
                "scope" : "STANDARD",
                "key" : "TARGET_AREA"
            }
        ],
        "description" : "XPTO"
    }
],
"scope" : "STANDARD" }

如何同时进行?

编辑

我正在尝试这种方式:

var cursor = db.getCollection('CollectionX').find({
  "scenario": "SCENARIOX",
  "stepConfigs.stepType": "STEPX",
  "stepConfigs.configs.key": "TARGET_AREA"
});

if (cursor.hasNext()) {
    var doc = cursor.next();
    doc.stepConfigs.find(function(v,i) { 
        if (v.stepType == "STEPX") {
           doc.stepConfigs[i].configs.find(function(w,j) {
                if (w.key == "TARGET_AREA") {
                    var result = db.getCollection('CollectionX').update(
                        { "_id" : doc._id },
                        { "$set" : { doc.stepConfigs[i].configs[j].targetAreaId: "VISUAL_MESSAGE" }}
                    );
                }
           });
        };
    });
} else {
    print("Step does not exist");
}

但是发生以下错误:

错误:第15行:意外的令牌。

1 个答案:

答案 0 :(得分:0)

我认为不可能。

您可以使用此查询更新所需的特定元素:

db.test_array.updateOne({}, {
    $set: {
        "stepConfigs.$[firstArray].configs.$[secondArray].targetAreaId": "VISUAL_MESSAGE"
    }
}, {
    arrayFilters: [{
        "firstArray.stepType": "STEPX"
    }, {
        "secondArray.targetAreaId": "USER_MESSAGE"
    }]
})

但是同时推送相同的数组确实会呈现此效果(这是针对原始模型的,但这仍然是相同的问题,您不能以这种方式在同一数组中进行$ set和$ push):

> db.test_array.updateOne({"step.type":"B"},{$push:{"step.$.configs":{"className":"something"}}, $set:{"step.$.configs.$[secondArray].targetAreaId":"TA-1"}},{arrayFilters:[{"secondArray.targetAreaId":"TA-2"}]})
2019-09-06T13:53:44.783+0200 E QUERY    [js] WriteError: Updating the path 'step.$.configs.$[secondArray].targetAreaId' would create a conflict at 'step.$.configs' :