2015-11-05 99 views
1

在spring-data-mongodb的Criteria运算符中,两个日期之间的差是否大于0?我写下面的查询:Datediff in Criteria operator in spring-data-mongodb does not working

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}}}]} 

问候

克里斯

+0

您能向我们展示您试图实现的完整逻辑mongodb查询吗? – chridam

+0

添加了mongodb查询 – chiku

回答

0

对于它的工作,你基本上要在当前聚合管道转换对此:

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") 
); 
+0

仍然无效,查询返回的行为ZERO – chiku

+0

仅供参考currentDate不是java.util.Date类型,currDate是集合中的另一个字段。 – chiku

+0

@chiku我已经在这种情况下更新了答案。 – chridam