首页 > 解决方案 > Spring Aggregation更新多个数组元素

问题描述

当它们的 ID 存在于列表中时,我正在尝试更新嵌套数组中的许多对象。

这是文档结构

{
    id: p00,
    children: [{
            id: c00,
            value: false
        },
        {
            id: c01,
            value: false
        },
        {
            id: c02,
            value: false
        }
    ]
}

我想更新所有数组元素value=trueifid=p00children.id in [c00, c01].

使用 aMatchOperation查找 id=p00 并传递给AggregationUpdate,我什至无法更新所有数组元素。

MatchOperation matchStage = Aggregation.match(
    new Criteria("id").is("p00"));
        
    AggregationUpdate update = AggregationUpdate.newUpdate(matchStage)
        .set("children.$.value").toValue(true);
        
    template.update(Parent.class)
        .apply(update)
        .all();

抛出异常:

org.springframework.dao.DataIntegrityViolationException: Invalid $set :: caused by :: FieldPath field names may not be empty strings.; nested exception is com.mongodb.MongoWriteException: Invalid $set :: caused by :: FieldPath field names may not be empty strings.

有什么问题?$ 语法应该返回嵌套数组元素。

标签: javamongodbspring-data-mongodb

解决方案


推荐阅读