2015-11-05 82 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