1

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 ?

1 Answer 1

5

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();
}
Sign up to request clarification or add additional context in comments.

5 Comments

Does your code issue all the queries at once during execute ? I don't want to issue multiple queries to mongodb
It is not possible to do it in one query but you can batch them as I have shown for efficient updates. It issues 100 queries at once.
Np. You can use BulkOperations bulkOps = mongoOperation.bulkOps(BulkOperations.BulkMode.UNORDERED, collectionname);
Thanks for your help. figured the collectionsName part, so deleted that comment. Is there a limit on the batch size ? any permissible limits or recommended values ?
Np. I'll test out with different limits and see which one is optimal. Read here

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.