javamongodbnosqlmongotemplate

MongoTemplate update multiple Document with at once without using saveAll() or loops


I'm having trouble saving multiple document at once, my need is that while update multiple document it updates only the targeted field: What i'm trying to do :

Update1 ("field Name" , " AB" ) ;
Update2 ("field Name", "ABC");
Query query = mongoTemplate.Aggr(...)

mongoTemplate.multipleUpdate(..,Update1, Update 2);

Is there any way possible to do this?


Solution

  • i figured out myself by using BulkOperations you can stack multiple Update into bulks and then execute it at the same time! My code:

    BulkOperations bulkOperations = mongoTemplate.bulkOps(BulkOperations.BulkMode.UNORDERED, Foo.class);
    
            List<Foo> fooList = FooRepository.findAllByIdIn(Arrays.asList(id));
            for (Foo foo : fooList) {
                Query query = new Query().addCriteria(new Criteria("...").is(...));
                Update update = new Update().set(..., ...);
                bulkOperations.updateOne(query, update);
            }
            bulkOperations.execute();