chiku
chiku

Reputation: 433

Datediff in Criteria operator in spring-data-mongodb not working

Can I have difference between two dates to greater than 0 in Criteria operator in spring-data-mongodb? I wrote the query below :

  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))));

This query not working. If possible please help me in getting this query work with spring-data-mongodb.

Edit: The mongodb pipeline query is as follows:

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

Regards

Kris

Upvotes: 1

Views: 2524

Answers (1)

chridam
chridam

Reputation: 103425

For it to work, you'd essentially want to convert the current aggregation pipeline to this:

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);

The Spring Data MongoDB equivalent follows:

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

Upvotes: 1

Related Questions