我想使用spring Boot 更新mongodb中的子菜单项字段

dfty9e19  于 2023-01-04  发布在  Spring
关注(0)|答案(1)|浏览(135)

我正在尝试更新子菜单项字段"active = true"子菜单项是MenuItems的一部分
它是一个嵌套文档,类似于

{
   "title": "home", 
   "active": false,
   "level": "1",
   "children": [
        {
            "title": "clothing",
            "type": "sub",
            "active": false,
            "level": "2",
        }
   ]
}

这是我的控制器补丁更新子菜单项字段的Map
我正在尝试使用Query (Criteria)更新此内容,但它不起作用

@PatchMapping("/menus-items-childrens/{id}")
    public MenuItems updateSubMenuItems(@RequestBody MenuItems menuItems, @PathVariable("id") long id) {
        Optional<MenuItems> tems = menuRepository.findById(id);
        MenuItems menuData = tems.get();

        Query query = new Query();
        query.addCriteria(Criteria.where("id").is(id).and("MenuItems.$.children")
                .elemMatch(Criteria.where("MenuItems.$.children.id").is(id)));
        Update update = new Update().set("MenuItems.$.children.active", true);

        System.out.println("---------------ok");

        return MongoOperations.findAndModify(query, update, MenuItems.class);

    }

告诉我,我调试了应用程序很多次,但是这个查询不起作用,我无法理解
我要更新嵌套文档

oymdgrw7

oymdgrw71#

试试这个(并阅读infos代码中的注解):

@PatchMapping("/menus-items-childrens/{id}")
public MenuItems updateSubMenuItems(@RequestBody MenuItems menuItems, @PathVariable("id") long id) {
        
    Query query = new Query();

    // assuming you want to update all the nested documents given the id of the main document
    // you only need to filter on the id field
    query.addCriteria(Criteria.where("id").is(id));

    // '$[]' is required to update all nested documents
    Update update = new Update().set("children.$[].active", true);
    
    return MongoOperations.findAndModify(query, update, MenuItems.class);

}

See https://www.mongodb.com/docs/drivers/node/current/fundamentals/crud/write-operations/embedded-arrays/#matching-all-array-elements for more info

相关问题