Reputation: 13
Using spring data mongo driver, I want to update multiple documents in mongodb using one single query and these documents will have a different updated value. I tried the following code but it would have the same updated value for all the documents that match the query criteria.
List<Criteria> bigCriteria = new ArrayList<Criteria>();
for (MyClass myClass : myClasses){
Criteria criteria = Criteria.where("_id").is(myClass.getId());
bigCriteria.add(criteria);
}
//next line is just a psedudo code to explain what I intend to do here
query = <<create an or query using bigCriteria created above>>;
Update update = new Update();
update.set("age":11);
mongoOperation.updateMulti(query, update, User.class);
Is there a way to update all the documents with different values ?
Upvotes: 1
Views: 5325
Reputation: 75994
You can use Bulk Write api to send batches of document to server with different query criteria and update document.
Something like
int count = 0;
int batch = 100;
BulkOperations bulkOps = mongoOperation.bulkOps(BulkOperations.BulkMode.UNORDERED, User.class);
for (MyClass myClass : myClasses){
Query query = new Query();
Criteria criteria = Criteria.where("_id").is(myClass.getId());
query.addCriteria(criteria);
Update update = new Update();
update.set("age", myClass.getAge());
bulkOps.updateOne(query, update);
count++;
if (count == batch) {
bulkOps.execute();
count = 0;
}
}
if (count > 0) {
bulkOps.execute();
}
Upvotes: 5