Himanshu Kansal
Himanshu Kansal

Reputation: 552

Mongo match in aggregate not working for date using java

I am using mongoDB java driver to query transactions between date range with aggregate framework. I am trying to use following mongo query:

db.orders.aggregate([
{ "$match":{
    "order_commit_time": {
        "$gte": ISODate("2015-04-30T18:30:00.000Z"),
        "$lte": ISODate("2016-08-23T19:53:23.000")
    }
}
},
{
"$unwind": "$discounts_list"
}, {
"$unwind": "$discounts_list.discount_split"
}, {
"$group" :{
    "_id": null,
    count:{$sum:1}
}
}]
);

The java code I am using to make query is following:

Date startDate = new Date(period.getStartTime().getTimeInMillis());
Date endDate = new Date(period.getEndTime().getTimeInMillis());

BasicDBObject match = new BasicDBObject("$match", new BasicDBObject(mongoDateField, 
    new BasicDBObject("$gte", startDate).append("$lte", endDate)));
BasicDBObject discount_list = new BasicDBObject("$unwind", "$discounts_list");
BasicDBObject discount_split = new BasicDBObject("$unwind", "$discounts_list.discount_split");
BasicDBObject group = new BasicDBObject("$group", new BasicDBObject("_id", null)
    .append("count", new BasicDBObject("$sum", 1)));
AggregationOutput output = mongoCollection.getCollection().aggregate(match, discount_list, discount_split, group);

But this java query is returning empty result. However if I use the mongo query on console, it is working fine. Also if I remove match from aggregation, query works fine but don't filter the result according to date. Moreover the same "match" DBObject, when used in count or find as query, works fine like this:

query = new BasicDBObject(mongoDateField, new BasicDBObject("$gte", startDate).append("$lte", endDate));
mongoCount = mongoCollection.getCollection().count(query);

Is there any way to convert the mongo query to java equivalent.

Thanks in advance.

Upvotes: 3

Views: 1899

Answers (2)

Raghavan
Raghavan

Reputation: 41

Did you try this?

BasicDBObject match = new BasicDBObject("$match", new BasicDBObject(mongoDateField, 
    new BasicDBObject("$gte", period.getStartTime().getTimeInMillis()).append("$lte", period.getEndTime().getTimeInMillis())));

I just released a new annotation based library that works like the Spring Data @Query annotation but for aggregation queries. This will eliminate all the boiler plate code and allow you to execute aggregate queries just by declaring this annotation on the repository interface methods. It also works with the date parameter as a long.

Upvotes: 1

Lakmal Vithanage
Lakmal Vithanage

Reputation: 2777

Just use "allowDiskUse(true)", as follow,

AggregationOutput output = mongoCollection.getCollection().aggregate(match, discount_list, discount_split, group).allowDiskUse(true);

Upvotes: 1

Related Questions