Hi I am using the Java API for connecting to my DB. I am using the new Classes to connecto since the ones in almost all examples are marked deprecated I use MongoClient to connect to MongoDatabase db. After that I do:
MongoCollection<Document> coll = db.getCollection("collName");
AggregateIterable<Document> res = collection.aggregate(myquery);
for(Document d : res)
{
System.out.println(d.toJson());
}
It doesn't print anything. I tried to use result.first() too but it only prints null.
Now the reason I don't post specifics about my data an query is the following. If I look in the the log file in /var/log/mongodb I see the translated query. If I post THE EXACT query into the mongo shell. It just works like a charm. I found a post on here the says that the order of my aggregate functions could be a problem but that doesn't make sense if it works if pasted in the shell.
So here is my little altered query
Document sort = new Document("$sort", new Document("Day", 1));
Document matchBeforeUnwindDayOfTheWeek = new Document("Day", day);
Document matchBeforeUnwindVar1 = new Document("'value.Data'", new Document("$elemMatch",
new Document("var1", new Document("$gt", minvar1).append("$lt", maxvar1))));
Document matchBeforeUnwindVar2 = new Document("'value.Data'", new Document("$elemMatch",
new Document("var2", new Document("$gt", mingvar2).append("$lt", maxvar2))));
List<Document> matchBeforeUnwindAnd = new LinkedList<Document>();
matchBeforeUnwindAnd.add(matchBeforeUnwindDayOfTheWeek);
matchBeforeUnwindAnd.add(matchBeforeUnwindVar1);
matchBeforeUnwindAnd.add(matchBeforeUnwindVar2);
Document matchBeforeUnwind = new Document("$match", new Document("$and", matchBeforeUnwindAnd));
Document unwind = new Document("$unwind", "$value.Data");
Document matchAfterUnwindVar1 = new Document("'value.Data.var1'",
new Document("$gt", minvar1).append("$lt", minvar1));
Document matchAfterUnwindVar2 = new Document("'value.Data.var2'",
new Document("$gt", minvar2).append("$lt", maxvar2));
List<Document> matchAfterUnwindAnd = new LinkedList<Document>();
matchAfterUnwindAnd.add(matchAfterUnwindVar1);
matchAfterUnwindAnd.add(matchAfterUnwindVar2);
Document matchAfterUnwind = new Document("$match", new Document("$and", matchAfterUnwindAnd));
Document groupFields = new Document("_id", "$_id");
groupFields.put("Grouped", new Document("$push", "$value.Data"));
Document group = new Document("$group", groupFields);
List<Document> query = new LinkedList<Document>();
query.add(sortByDayOfTheWeek);
query.add(matchBeforeUnwind);
query.add(unwind);
query.add(matchAfterUnwind);
query.add(group);
AggregateIterable<Document> result = collection.aggregate(query);
Edit: I tried it with a very simple query like the one posted below. Queries still translate fine in the log file.