如何在java中更新集合中特定索引处对象的数组List


public Class Customer{
private long id;
private String name;
private String companyName;
private List<Environment> environment = new ArrayList<>();
}
public Class Environment{
private int clusterid;
private string clusterName
}
My Collection in Mongo DB

{  
"id":1,
"name":"xyz",
"companyName":"abc",
"environment":[
{
"clusterid":2,
"clusterName":"qwe"
},
{
"clusterid":6,
"clusterName":nme"
}
]
}
want to update environment List of index 1 with returning whole environment List. How do I do this with spring boot? I want to update particular index of list fetching other too in the collection .
public int updateEnv(Customer customer) {
Query query = new Query();
query.addCriteria(Criteria.where("id").is(customer.getid()));
Update update = new Update();
update.set("environment", customer.getEnvironment());
return mongoUtil.update(query, update, Customer.class);
}

此查询使用列表中的值而不是特定索引处的值更新整个环境列表。请指导位置运算符。如何在java 中使用位置运算符

您应该能够将索引传递给update查询。因此,如果您想更新/替换索引1处的元素,可以执行以下操作:

update.set("environment.1", customer.getEnvironment())

尝试此更新的查询。

更新的Mongo Playground

db.collection.update({
id: 1/**customer id*/

},
{
"$set": {
"environment.$[element]": {
"clusterId": 4,
/**environment object with updated clusterId*/
"clusterName": "asd"/**environment object with updated clusterName*/

}
}
},
{
arrayFilters: [
{
"element.clusterid": 6/**clusterId of environment you have to update*/

}
]
})

最新更新