how can i convert this mongodb aggregation command to java:
to give you a global vision of what i want; i will give more details; i have a collection called "Finance" and within this collection there are many documents that have different types; i want only those with type expenses:{type:"expenses"} so documents with expenses type have a field called bought_date; and it is in milliseconds, and also those documents have field called price. i want the total of price within each month! so i need to convert those milliseconds to date to be able to regroup it using $month!
db.Finance.aggregate([ { $match : { type : "Expenses" } } ,{
"$project": {
"bought_date": {
"$add": [ new Date(0), "$bought_date" ]
},
"msisdn": 1
}
},
{
"$group" : {
"_id" : {
"bought_date" : "$bought_date",
"msisdn":"$msisdn"
},
"msisdnCount" : { "$sum" : 1}
}
}
]);
i tried this:
JsonObject first_match=new JsonObject()
.put("type", "Expenses");
JsonObject project=new JsonObject()
.put("bought_date", new JsonObject()
.put("$add",new JsonArray()
.add(new Date(0))
.add("$bought_date")))
.put("msisdn", 1);
JsonObject project_sec=new JsonObject()
.put("month",new JsonObject().put("$month","$bought_date"))
.put("msisdn", 1)
.put("bought_date", 1);
JsonObject group=new JsonObject()
.put("_id","$month")
.put("price",new JsonObject()
.put("$sum","price"));
JsonArray pipeline=new JsonArray()
.add(new JsonObject().put("$match", first_match))
.add(new JsonObject().put("$project", project))
.add(new JsonObject().put("$project", project_sec))
.add(new JsonObject().put("$group", group));
JsonObject command = new JsonObject()
.put("collection", "Finance")
.put("pipeline",pipeline)
.put("explain",false);
//using RunCommand
client.runCommand("aggregate",command, results -> { ...
but it looks like i can't add a date into JsonArray? : Illegal type in JsonObject: class java.util.Date
Solution in case someone was facing the same problem: my problem was with new Date(0) which wasn't a type that can be added to JsonObject, so i instead used this: new JsonObject().put("$date", "1970-01-01T00:00:00Z")