'Ways to update many nested Documents with MongoTemplate without creating additional Update object

I use MongoTemplate to update a document using findAndModify() method. There are nested documents inside one document. Example as following:

@Document
public class Company {
    private Long id;
    private String postalCode;
    private int floorCount;
    .....

    private Set<Car> cars;
}

class Car {
    private Long id;
    private int seatCount;
    private String color;
    .....
    private Engine engine;
}

class Engine {
    private Long id;
    private float engineVolume;
    .....   
}

In order to send to findAndModify() method as a parameter, I created an Update object for a Company as following:

Update update = new Update();
update.set("postalCode", company.getPostalCode());
update.set("floorCount", company.getFloorCount());
....

There are many Cars for a Company and update requests of Company comes with Car and Engine details. To update Cars of Company, for nested Car documents, I write another separate findAndModify() method as following:

company.getCars().forEach(
                car -> {
                    mongoTemplate.findAndModify(
                            new Query(where("car._id").is(car.getId())),
                            new Update()
                                    .set("car.$[].seatCount", car.getSeatCount())
                                    .set("car.$[].color", car.getColor()),                                   
                            Car.class
                    );
                }
        );

What I want to do is I would like to build only one Update object for entire Company document with Car and Engine and set new values to only one Update object without iterating over Cars and without using another separate findAndModify() method for Car. How can I do?



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source