我需要每天在每个文档中找到所有值的总和。
文档结构是:
{
"utc_ts":1333333333,
"value":33
}
数据库查询
db.getCollection('collection').aggregate([{
"$project":{
"_id": 1,
"value":1,
"y": {
"$year": {
"$add": [
new Date(0),"$utc_ts"
]
}
},
"m": {
"$month": {
"$add": [
new Date(0),"$utc_ts"
]
}
},
"d": {
"$dayOfMonth": {
"$add": [
new Date(0),"$utc_ts"
]
}
}
}
},{
"$group": {
"_id": {
"year": "$y",
"month": "$m",
"day": "$d"
},
"count" : {"$sum":"$value"}
}
}]);
我尝试使用 Morphia 执行此操作。
AggregationPipeline pipeline = this.getDatastore().createAggregation(Log.class)
.match(q)
.project(
projection("y", expression("$year",
new BasicDBObject("$add",
Arrays.asList(new Date(0), "$utc_ts")))),
projection("value"## Heading ##),
projection("m", expression("$month",
new BasicDBObject("$add",
Arrays.asList(new Date(0), "$utc_ts")))),
projection("d", expression("$dayOfMonth",
new BasicDBObject("$add",
Arrays.asList(new Date(0),"$utc_ts")))))
.group("_id",
grouping("sum", sum("value")));
Iterator<Aggregate> aggregate = pipeline.aggregate(Aggregate.class, builder().outputMode(CURSOR).build());
此代码无效。如何解决这个问题? 而不是所需的格式,
{
"_id" : {
"year" : 2018,
"month" : 6,
"day" : 12
},
"sum" : 40
}
它正在返回
{
"sum": 1
}
另外,这是最佳方法吗?
我在这个答案的帮助下得到了查询:answer