更新mongodb中的嵌套数组元素

时间:2019-11-20 12:05:19

标签: mongodb typescript multidimensional-array

在我的情况下,我有带有嵌套数组的mongodb文档,并且需要更新属性数组元素。我的mongodb文件如下。

{
"_id" : ObjectId("5dca9c5ece5b91119746eece"),
"updatedAt" : ISODate("2019-11-20T11:48:55.339Z"),
"attributeSet" : [ 
    {
        "attributeSetName" : "test-0",
        "type" : "Product",
        "id" : "1574158032603",
        "updatedAt" : ISODate("2019-11-19T10:10:53.783Z"),
        "createdAt" : ISODate("2019-11-19T10:07:20.084Z"),
        "attributes" : [ 
            {
                "attributeName" : "test-attribute",
                "defaultValue" : 123,
                "isRequired" : false,
                "id" : "1574221129398"
            }, 
            {
                "attributeName" : "test-attribute-02",
                "defaultValue" : 456,
                "isRequired" : false,
                "id" : "1574250533840"
            }
        ]
    }, 
    {
        "attributeSetName" : "test-1",
        "type" : "Product",
        "id" : "1574158116355",
        "updatedAt" : ISODate("2019-11-19T10:08:37.251Z"),
        "createdAt" : ISODate("2019-11-19T10:08:37.251Z"),
        "attributes" : []
    }
  ]
}

我需要更新属性数组中的元素,并将更新文档放入结果对象。这是我到目前为止尝试过的。

const result = await this.model.findOneAndUpdate(
{
    _id: settingsToBeUpdated._id,
    "attributeSet": {
        $elemMatch: {
            "attributeSet.id": attributeSetId,
            "attributes": {
                $elemMatch: {
                    'attributes.id': id
                }
            }
        }
    }
},
{
    $set: {
        'attributeSet.$[outer].attributes.$[inner].attributeName': attributeDto.attributeName,
        'attributeSet.$[outer].attributes.$[inner].defaultValue': attributeDto.defaultValue,
        'attributeSet.$[outer].attributes.$[inner].isRequired': attributeDto.isRequired,
    }
},
{
    "arrayFilters": [
        { "outer.id": attributeSetId },
        { "inner.id": id }
    ]
}
);

它不会更新模型。我指的是this link,但没有帮助。 任何建议将不胜感激。

1 个答案:

答案 0 :(得分:0)

在查询中需要纠正的夫妇,否则几乎就可以了。由于$elemMatch的{​​{1}}(文档数组)字段将在要过滤的这些文档的 attributeSet 属性上而不是在 attributeSet.id ,它不知道它是什么。并且不需要嵌套的elemMatch,只需使用点表示法

要进行调试,您可以使用查找查询进行尝试。

查询(Shell):

id
相关问题