for this question?
https://stackoverflow.com/questions/72055175/ways-to-update-many-nested-documents-with-mongotemplate-without-creating-additio
Hi. 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: companyRequest.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()), Company.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 and use only one findAndModify(), requirement is to send only one request to MongoDB. How can I do?
What exact fields are you trying to update in "cars" sub-documents? Your code as it is right now, doesn't seem to effectively change anything. I mean, it feels like the effect is car[0].seatCount = car[0].seatCount, then next car[1].seatCount = car[1].seatCount and so on. Which means that you're setting values in db to the same values they were before. Or am I missing something? Can you please clarify what is the business goal of the query you're trying to compose? E.g. - "I want to update postal code of company and paint all cars to green in a single query". Something like that
companyRequest is the request coming from front end. And as I show, I want to update the fields of Car class and Company fields with only one query to MongoDB . Goal is written at the end of the question. What else would you like to know about question?
Ah, ok, got it. Now companyRequest makes sense to me. Still this part is not clear for me though: update.set("postalCode", company.getPostalCode()); update.set("floorCount", company.getFloorCount()); new values for postal code and floor count are fetched from company object, not companyRequest, right? Where that company object comes from?
Обсуждают сегодня