java mongodb group分组使用

mongodb的关键字及介绍.mongodb的查询是有一定规则的,刚开始接触老是各种错误,参照以下内容有很多帮助

https://docs.mongodb.com/manual/reference/sql-aggregation-comparison/

另外出现这种错误时A pipeline stage specification object must contain exactly one field 是因为条件不对,参照上面网址里面的内容

上面网址里面的内容很重要我就不重复了,自己看

下面是我写的例子

//group
DBObject groupFields = new BasicDBObject( "_id", "$day");
groupFields.put("count", new BasicDBObject( "$sum", "$increase"));
DBObject group = new BasicDBObject("$group", groupFields);

//where条件
Calendar date = Calendar.getInstance();
date.set(Calendar.DATE, date.get(Calendar.DATE) - dateCnt);
DBObject condition1 = new BasicDBObject();
condition1.put("blockId", blockId);
condition1.put("createTime", new BasicDBObject("$gte", date.getTimeInMillis()));
DBObject match = new BasicDBObject("$match", condition1); //$match相当于where

//排序
DBObject sortFields = new BasicDBObject("_id", 1);
// 注意此处排序是按照字段day升序,但是不能写day 需用_id代替,因为day是group用的字段
DBObject sort = new BasicDBObject("$sort", sortFields);

List optionList = new ArrayList<>();
optionList.add(match);
optionList.add(group);
optionList.add(sort);
//optionList中的顺序很重要,不是随便往list里面加的,否则是不正确的,添加的顺序也是参照上面网址里面的内容
AggregationOutput output = xMapper.getMongoTemplate().getCollection().aggregate(optionList);
上面代码实现的sql功能

select day, sum(increase) as count from table where blockId = 'XXXX' and createTime >= XXXX group by day order by day asc


你可能感兴趣的:(mongodb,java,mongodb,group)