Using the MongoDB FirstFirst Method

I am using MongoTemplate UpdateFirst () to update an internal document. But the update operation does not work.

my Mongo collection structure:

{
"_id" : ObjectId("540dfaf9615a9bd62695b2ed"),
"_class" : "com.springpoc.model.Awards",
"brand" : [ 
    {
        "name" : "Brand1",
        "descr" : "Desc1"
    }
],
"name" : "Award1",
"narname" : "Nar1"

}

Java Code:

mongoTemplate.updateFirst(
query(where("name").is("Award1")), 
Update.update("brand.$.descr", "Desc2"),
Awards.class);  

Premium Class Structure

public class Awards {

private String id;
List<Brand> brand = new ArrayList<Brand>();
private String name;
private String narname;

Brand Class Structure

public class Brand {
private String name;
private String descr;

Any suggestions on updating the Brand.Name document to a new value.

0
source share
1 answer

If you want to use the operator $in the update part, you must explicitly write that arrayin the request part. So,

mongoTemplate.updateFirst(
query(where("name").is("Award1")), 
Update.update("brand.$.descr", "Desc2"),
Awards.class);

it should be

mongoTemplate.updateFirst(
query(where("name").is("Award1"))
.and("brand.name").is("Brand1"), // "brand" in "brand.name" is necessary, others according to your requirement
Update.update("brand.$.descr", "Desc2"),
Awards.class);

If you know the position of the element in the array, `$ 'is not necessary, you can try the following:

mongoTemplate.updateFirst(
query(where("name").is("Award1")), 
Update.update("brand.0.descr", "Desc2"), // 0 is the index of element in array
Awards.class);

The same way of processing the field name.

0
source

Source: https://habr.com/ru/post/1607874/


All Articles