Is it possible to find, compare and modify the fields in several rows using a single query?

29 Views Asked by At

I am using MongoTemplate to accomplish my task with 2 queries. But wanted to know if it's possible to do the same with a single query. Example-

  1. Filter the records based on a boolean value (isSaved),
  2. In each record pick the field(boughtDate) and check if it was bought yesterday.
  3. If yes, then update the field(isPromoValid) to true.

What I do now is. I just query to get the records based on a filter condition. Locally do date comparison on each record's Date field. Then use updateMany to update all the records

1

There are 1 best solutions below

0
Manoj On
BulkOperations bulkOps = template.bulkOps(BulkOperations.BulkMode.UNORDERED, UserEntity.class);
       
Criteria criteria1 = Criteria.where(isSaved).is(false);
Criteria criteria2 = Criteria.where(boughtDate).lte(Utility.Today);

Query query = new Query(criteria1.andOperator(criteria2));

        
Update update = new Update();
update.set(isPromoValid, true);
            
bulkOps.updateMulti(query, update);
BulkWriteResult result = bulkOps.execute();