简体   繁体   English

如何在 spring 数据 MongoDB 中使用 $where?

[英]How can I use $where in spring data MongoDB?

I am not able to use $where in SpringDataMongoDb .我无法在SpringDataMongoDb中使用$where

Is there any way to achieve this in SpringBoot ?有什么方法可以在SpringBoot中实现这一点?

db.getCollection('my_collection').find({ $where : function(){
    for (var key in this.action_status){
        return this.action_status[key] == false;
    }
}})

Thank You.谢谢你。

1: You can create a repository that extends MongoRepository and have a JSON Query method as follows: 1:您可以创建一个扩展MongoRepository的存储库并具有JSON查询方法如下:

@Query("{'action_status':{$eq:?0}}")
public List<YourObj> findByActionStatus(boolean status);

2: You can use Query By Object Attribute in MongoRepository. 2:您可以在 MongoRepository 中使用 Query By Object 属性。 Supposedly you have a field called "isActionStatus" in your object, just declare this method in your repository:假设您的 object 中有一个名为“isActionStatus”的字段,只需在存储库中声明此方法即可:

public List<YourObj> findByIsActionStatus(boolean actionStatus);

Spring Data will break the method name like "select * from... where isActionStatus = actionStatus Spring 数据会破坏方法名称,如“select * from... where isActionStatus = actionStatus

If you need a more complex query you can find the supported keywords here: https://docs.spring.io/spring-data/mongodb/docs/1.2.0.RELEASE/reference/html/mongo.repositories.html If you need a more complex query you can find the supported keywords here: https://docs.spring.io/spring-data/mongodb/docs/1.2.0.RELEASE/reference/html/mongo.repositories.html

It can be implemented in two ways one is using MongoTemplate and criteria query in spring boot application它可以通过两种方式实现,一种是在 spring 启动应用程序中使用 MongoTemplate 和条件查询

Query query = new Query();
query.addCriteria(Criteria.where("action_status").eq(false));
List<User> users = mongoTemplate.find(query,MyCollectionClassName.class);

Another way is using mongo repository另一种方法是使用 mongo 存储库

@Query("SELECT mc FROM my_collection mc WHERE mc.status = false")
MyCollectionClassName findMyCollectionClassNameByStatus(Integer status);

References:参考:

https://www.baeldung.com/queries-in-spring-data-mongodb
https://www.baeldung.com/spring-data-jpa-query

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

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