简体   繁体   English

如何将自定义 Mongo DB 更新查询转换为 Java 代码

[英]How to convert custom Mongo DB update query to Java code

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: {
        $toUpper: '$recipientEmail'
      },
      senderEmail: {
        $toUpper: '$senderEmail'
      }
    }
  }
],{ multi: true })

But now I am trying to convert this query into Java code, I am not able to convert it.但是现在我试图将此查询转换为 Java 代码,我无法转换它。 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?那么,谁能帮我将此查询转换为 Java 代码,以便我可以在 Spring 启动应用程序中使用它? Thanks in advance.提前致谢。

You can use @Query annotation in your repository interface and pass your query as it is (above the method signature).您可以在存储库接口中使用 @Query 注释并按原样传递您的查询(在方法签名上方)。 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}}"
            + "]}")

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);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM