mongoDb数据库操作
数据库命rawdata
时间按天分组使用$dateToString 用法见https://blog.csdn.net/u013066244/article/details/53842355
db.rawdata.aggregate([{$match:{analyze_time: {'$gte': new Date('2018-09-01'), '$lt': new Date('2018-09-30')},"crawler.country_id":{'$in':['4028c7d5-64eec376-0164-eeff256b-0030']}}}, {$group:{_id:{date:{$dateToString: {format: "%Y-%m-%d", date: "$analyze_time"}},countryId:"$crawler.country_id"},count:{$sum:1}}},{$sort:{"_id":1}}]);
java代码(springboot下jpa操作数据库)
//$match Document documentMatch= new Document();
documentMatch.put("analyze_time",new Document("$gt", sdf.parse(startDate)).append("$lte", sdf.parse(endDate)));
//$group SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm");
Map map=new HashMap();
map.put("format","%Y-%m-%d");
map.put("date","$analyze_time");
Document groupFiles=new Document();
groupFiles.put("date",new Document("$dateToString", map));
Document documentGroup= new Document();
documentGroup.put("_id",groupFiles);
documentGroup.put("count", new Document("$sum", 1));
//$sort
Document documentSort= new Document();
documentSort.put("_id",1);
Document match = new Document("$match", documentMatch);
Document group = new Document("$group", documentGroup);
Document sort = new Document("$sort", documentSort);
List aggregateList = new ArrayList();
aggregateList.add(match);
aggregateList.add(group);
aggregateList.add(sort);
AggregateIterable resultset = mongoTemplate.getCollection("rawdata").aggregate(aggregateList);
MongoCursor cursor = resultset.iterator();
List listDate =new ArrayList();
List listCount =new ArrayList();
while(cursor.hasNext()) {
Document item_doc = cursor.next();
Document document = (Document) item_doc.get("_id");
int count = item_doc.getInteger("count", 0);
}