【问题标题】:Datediff in Criteria operator in spring-data-mongodb not workingspring-data-mongodb 中 Criteria 运算符中的 Datediff 不起作用
【发布时间】:2015-11-05 04:16:52
【问题描述】:

我可以在 spring-data-mongodb 中的 Criteria 运算符中使两个日期之间的差异大于 0 吗?我在下面写了查询:

  Criteria c= Criteria.where("myDate").gte(startDate).
               andOperator(Criteria.where("myDate").lte(endDate).andOperator(Criteria.where("studentId").is(studentId).andOperator(Criteria.where("currDate - myDate").gt(0))));

此查询不起作用。 如果可能的话,请帮助我让这个查询与 spring-data-mongodb 一起工作。

编辑: mongodb管道查询如下:

 { "aggregate" : "__collection__" , "pipeline" : [ { "$match" : { "myDate" : { "$gte" : { "$date" : "2000-01-01T07:57:33.231Z"}} , "$and" : [ { "myDate" : { "$lte" : { "$date" : "2015-11-05T07:57:33.231Z"}} , "$and" : [ { "studentId" : "100" , "$and" : [ { "currDate - myDate" : { "$gt" : 0}}]}]}]}} , { "$project" : { "status" : 1}} , { "$group" : { "_id" : { "status" : "$status"} , "activeCount" : { "$sum" : 1}}}]}

问候

克里斯

【问题讨论】:

  • 您能否向我们展示您想要实现的完整逻辑 mongodb 查询?
  • 添加了 mongodb 查询

标签: spring mongodb spring-data-mongodb


【解决方案1】:

为了让它工作,你基本上想把当前的聚合管道转换成这样:

var pipeline = [ 
    { 
        "$project" : { 
            "status" : 1,
            "studentId" : 1,
            "myDate" : 1,
            "dateDifference": { "$subtract": [ new Date(), "$myDate" ] }
        }
    },
    { 
        "$match" : { 
            "studentId": "100" ,
            "myDate": { 
                "$gte": ISODate("2000-01-01T07:57:33.231Z"),
                "$lte": ISODate("2015-11-05T07:57:33.231Z")
            },
            "dateDifference": { "$gt" : 0 }         
        }
    },   
    { 
        "$group": { 
            "_id": "$status",           
            "activeCount": { "$sum" : 1 }
        }
    }
];

db.collection.aggregate(pipeline);

Spring Data MongoDB 等价物如下:

Criteria dateCriteria = new Criteria().andOperator(Criteria.where("myDate").gte(startDate).lte(endDate),
                                                   Criteria.where("dateDifference").gt(0));
Aggregation agg = Aggregation.newAggregation(       
    project("id", "status", "studentId", "myDate") 
        .andExpression("currDate - myDate").as("dateDifference"),
        //.and(currDate).minus("myDate").as("dateDifference"), <-- or use expressions
    match(Criteria.where("studentId").is("100").andOperator(dateCriteria)),
    group("status"), 
        .count().as("activeCount")
);

【讨论】:

  • 还是不行,查询返回的行数为零
  • 仅供参考,currentDate 不是 java.util.Date 类型,currDate 是集合中的另一个字段。
  • 它不起作用,从查询返回的行为零。请让我知道如何比较 spring-data-mongodb 中 where 子句中的两个日期字段?
  • 请参考此链接stackoverflow.com/questions/20800069/…,请查询
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-03-15
  • 1970-01-01
  • 2017-02-14
  • 1970-01-01
  • 2018-04-27
  • 1970-01-01
相关资源
最近更新 更多