How to convert custom Mongo DB update query to Java code

369 Views Asked by At

I was finding on the internet how to update all the document field values with lowercase. I luckily found a query which I modified as per my requirement and it is working correctly.

db.messages.updateMany({},
[
  {
    $set: {
      recipientEmail: {
        $toLower: '$recipientEmail'
      },
      senderEmail: {
        $toLower: '$senderEmail'
      }
    }
  }
],{ multi: true })

But now I am trying to convert this query into Java code, I am not able to convert it. I again started looking into the internet, but couldn’t find any code. So, can anyone help me convert this query to Java code so that I can use it in my Spring Boot application? Thanks in advance.

2

There are 2 best solutions below

2
Zabon On

You can use @Query annotation in your repository interface and pass your query as it is (above the method signature). Here is an example :

@Query("{$and:["
            + "     {'id': ?0},"
            + "     {$or:["
            + "         {'customerId': ?1},"
            + "         {'specificCode': ?4}"
            + "     ]},"
            + "     {'beginDate' : { $gte: ?2}},"
            + "     {$or:["
            + "             {'endDate' : { $lte: ?2}},"
            + "             {'endDate' : {$exists: false}}"
        
            + "     ]},"
            + "     {'numberOfTimesUsed': { $lt: ?3}}"
            + "]}")
14
Charchit Kapoor On

You can try something like this:

Query query = new Query();
Update update = new Update();
update.set("recipientEmail", StringOperators.valueOf("recipientEmail").toUpper());
update.set("senderEmail", StringOperators.valueOf("senderEmail").toUpper());
mongoTemplate.updateMulti(query, update, Messages.class);

Since you are aggregation pipeline form of update, you can try this:

Query query = new Query();
AggregationUpdate update = AggregationUpdate.update().set("recipientEmail").toValue(StringOperators.valueOf("recipientEmail").toUpper()).set("senderEmail").toValue(StringOperators.valueOf("senderEmail").toUpper());
mongoTemplate.updateMulti(query, update, Messages.class);