mongoTemplate按时间分组查询没有结果

a1exlee 2017-05-27 06:59:15
如题,文档结构如下:

需求:按照日期分组,求出每天的数据总数。

使用robomongo客户端查询两种方式均能查出结果。如下:
db.runCommand(
{ group :
{
ns: "Incident" ,
cond : { "$and" : [ { "source" : "外点机房动环"}]} ,
$reduce : function Reduce(doc, out) {
if(doc._id){
out.count +=1;
}
} ,
initial : { "count" : 0} ,
$keyf : function(doc){
var date = new Date(doc.lastOccurTime);
var dateKey = '' + date.getFullYear()+ '-' + (date.getMonth()+1) + '-' + date.getDate() ;
return {'day':dateKey};
}
}
}
)

结果:
db.getCollection('Incident').group({
keyf:function(doc){
var date = new Date(doc.lastOccurTime);
var dateKey = '' + date.getFullYear()+ '-' + (date.getMonth()+1) + '-' + date.getDate() ;
return {'day':dateKey}},
cond:{ "$and" : [ { "source" : "外点机房动环"}]},
initial:{"count":0},
reduce:function Reduce(doc, out) {
if(doc._id){
out.count +=1;
}}
})


结果:

现在按照网上的方式,使用spring的mongoTemplate查询却是空的,麻烦各位大牛帮忙看下java代码应该怎么写:
criteria.andOperator(Criteria.where("source").is("外点机房动环"));
Query query = Query.query(criteria);
BasicDBObject initial = new BasicDBObject();
initial.put("count", 0);
String reduce = "function Reduce(doc, out) { "
+ " if(doc._id){ "
+ " out.count +=1; "
+ " } "
+ " }";
String keyf = "function(doc){ "
+ " var date = new Date(doc.lastOccurTime); "
+ " var dateKey = '' + date.getFullYear()+ '-' + (date.getMonth()+1) + '-' + date.getDate() ; "
+ " return {'day':dateKey}; "
+ " }";
DBCollection collection = mongoTemplate.getCollection("Incident");
GroupCommand Gc = new GroupCommand(collection, keyf, query.getQueryObject(), initial, reduce, null);
logger.debug("GC:" + Gc.toDBObject().toString());
DBObject object = mongoTemplate.getCollection("Incident").group(Gc);
logger.debug("result:" + object.toString());




...全文
335 回复 打赏 收藏 转发到动态 举报
写回复
用AI写文章
回复
切换为时间正序
请发表友善的回复…
发表回复

81,092

社区成员

发帖
与我相关
我的任务
社区描述
Java Web 开发
社区管理员
  • Web 开发社区
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧