mongodb Monogodb:使用条件更新对象数组的元素

mi7gmzs6  于 2023-08-04  发布在  Go
关注(0)|答案(2)|浏览(120)

我有这个文件:

{
  "id" : "001",
  "items" : {
    "persons" : [ 
        {
            "city" : "London",
            "color" : "red",
            "status" : "1"
        }, 
        {
            "city" : "Paris",
            "color" : "blue",
            "status" : "0"
        }
     ],
    "animals" : [ 
        {
            "city" : "Luton",
            "color" : "red",
            "status" : "1"
        }, 
        {
            "city" : "London",
            "color" : "red",
            "status" : "0"
        }
     ]
}

字符串
在java中,或者至少直接在mongo中,我需要将人和动物的状态更新为数组中每个满足城市和/或颜色输入条件的项目的新值。* 身份是强制性的,城市和颜色不是强制性的。
例如:
输入city=伦敦color=redstatus=9将得到:

{
  "id" : "001",
  "items" : {
    "persons" : [ 
        {
            "city" : "London",
            "color" : "red",
            "status" : "9"
        }, 
        {
            "city" : "Paris",
            "color" : "blue",
            "status" : "0"
        }
     ],
    "animals" : [ 
        {
            "city" : "Luton",
            "color" : "red",
            "status" : "1"
        }, 
        {
            "city" : "London",
            "color" : "red",
            "status" : "9"
        }
     ]
}


inputcolor=redandstatus=7将导致:

{
  "id" : "001",
  "items" : {
    "persons" : [ 
        {
            "city" : "London",
            "color" : "red",
            "status" : "7"
        }, 
        {
            "city" : "Paris",
            "color" : "blue",
            "status" : "0"
        }
     ],
    "animals" : [ 
        {
            "city" : "Luton",
            "color" : "red",
            "status" : "7"
        }, 
        {
            "city" : "London",
            "color" : "red",
            "status" : "7"
        }
     ]
}


我试过很多方法,但都不管用。如果有人能拿出一个解决办法是很好的,但我会满足于一个建议来指导我解决这件事。

eqqqjvef

eqqqjvef1#

从你的问题中,我刚刚明白你想通过or的标准更新这2个对象personsanimals的状态。

Query query = Query.query(new Criteria().orOperator(
               Criteria.where("items.persons.city").is("your value"),
                       Criteria.where("items.persons.color").is("your value"),
                       Criteria.where("items.animals.city").is("your value"),
                       Criteria.where("items.animals.color").is("your value")
       ));
       Update update = new Update().set("items.$.status", "9");
mongoTemplate.updateFirst(query, update, "Your class name");

字符串

wkftcu5l

wkftcu5l2#

希望对你有帮助

{
$or: [
{
  "items.persons.color": "red"
},
{
  "items.animals.color": "red"
}
]
},
{
$set: {
"items.persons.$[elem].status": "7",
"items.animals.$[elem].status": "7"
}
},
{
 arrayFilters: [
{
  "elem.color": "red"
}
]
})

字符串
仅适用于颜色ex-https://mongoplayground.net/p/UTLAVWQ884V
同时适用于颜色和城市ex-https://mongoplayground.net/p/qRdi2c1VDQg

相关问题