Java implements date (Date) grouping function of MongoDB
In the previous blog post, I implemented the Group function of MongoDB through an encapsulated Java interface, but did not talk about how to query by date Date. Here is a supplement to how to improve the date Group function of MongoDB.
When implementing the Group function, there are usually some conditions attached, such as querying grouping only if the status is completed or incomplete, or querying eligible packets within a certain date and time period. At this point, if you set the eligible date count in Reduce, you will find that MongoDB completely ignores the date. Why? Because the grammar is wrong.
When querying the grouping of specific conditions in MongoDB, you should put those conditions in Condition. For more information on how to do this, look at the following code.
Public String getCTOStatistic () throws Exception {String ctoTaskType = getParameterValue ("ctoTaskType"). ToString (); String startDate = getParameterValue ("startDate"). ToString (); String endDate = getParameterValue ("endDate"). ToString (); DBObject initial = new BasicDBObject (); DBObject index = new BasicDBObject (); BasicDBObject cond = new BasicDBObject (); BasicDBObject dateCondition = new BasicDBObject (); index.put ("count", 0) Index.put ("ctoPerson", "); initial.put (" ctoPerson ", index); cond.put (" ctoStatus "," Finished "); if (StringUtils.isNotEmpty (ctoTaskType)) {cond.put (" taskId ", ctoTaskType);} if (StringUtils.isNotEmpty (startDate)) {dateCondition.append (" $gte ", DateUtil.toDate (startDate)) } if (StringUtils.isNotEmpty (endDate)) {dateCondition.append ("$lt", DateUtil.toDate (endDate));} cond.put ("jobCreateTime", dateCondition); String reduce = "function (doc, out) {" + "out.ctoPerson.count = out.ctoPerson.count+=1;" + "out.ctoPerson.ctoPerson = doc.ctoPerson" "+"} "; BasicDBList group = (BasicDBList) ctoJobService.group (new String [] {" ctoPerson "}, cond, initial, reduce, null); this.jsonResult = group.toString (); return SUCCESS;}