Spring Boot自定义查询MongoDB

标签 spring mongodb spring-boot mongorepository

我有这个 MongoDb 查询:

db.getCollection('user').find({
    $and : [
        {"status" : "ACTIVE"},
        {"last_modified" : { $lt: new Date(), $gte: new Date(new Date().setDate(new Date().getDate()-1))}},
        {"$expr": { "$ne": ["$last_modified", "$time_created"] }}
    ]
})

它在 Robo3T 中工作,但是当我将其作为自定义查询放入 spring boot 时,它会在项目启动时抛出错误。

@Query("{ $and : [ {'status' : 'ACTIVE'}, {'last_modified' : { $lt: new Date(), $gte: new Date(new Date().setDate(new Date().getDate()-1))}}, {'$expr': { '$ne': ['$last_modified', '$time_created']}}]}")
    public List<User> findModifiedUsers();

我尝试在 Spring 使用Criteria 进行查询:

Query query = new Query();
Criteria criteria = new Criteria();  
criteria.andOperator(Criteria.where("status").is(UserStatus.ACTIVE), Criteria.where("last_modified").lt(new Date()).gt(lastDay), Criteria.where("time_created").ne("last_modified"));

但它不起作用,它向我返回所有用户,就像没有最后一个条件不等于 last_modifiedtime_created 一样。

有谁知道可能是什么问题?

最佳答案

我认为 Criteria 尚不支持此功能 - 检查此 https://jira.spring.io/browse/DATAMONGO-1845 . 一种解决方法是像这样通过 mongoTemplate 传递原始查询:

BasicDBList expr = new BasicDBList();
expr.addAll(Arrays.asList("$last_modified","$time_created")); 

BasicDBList and = new BasicDBList();
and.add(new BasicDBObject("status","ACTIVE"));
and.add(new BasicDBObject("last_modified",new BasicDBObject("$lt",new Date()).append("$gte",lastDate)));
and.add(new BasicDBObject("$expr",new BasicDBObject("$ne",expr)));

Document document = new Document("$and",and); 
FindIterable<Document> result = mongoTemplate.getCollection("Users").find(document);

关于Spring Boot自定义查询MongoDB,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54668531/

相关文章:

java - 如何将 MySQL 查询的结果映射到 java 模型类?

Spring Boot - 来自依赖项的多个过滤器链

spring - 设置 Spring Profile 变量

mongodb - 使用 mongoDB 的动态嵌入式文档 - MongoEngine

python - 在数据库中缓存大型非 unicode 字典?

mongodb - 中断获取从 MongoDB 池中检索项目的许可

spring-boot - 开类 : Spring boot : log4j settings -- configuration and finding the application log file

spring-boot - 如何在 Grails 4 中设置日志级别

java - "Bean name must not be empty"具有 bean 名称的 spring bean 错误

java.lang.ClassNotFoundException : org. apache.http.util.Args - 我应该添加哪个依赖项?