码迷,mamicode.com
首页 > 其他好文 > 详细

mongoTemplate聚合操作Demo

时间:2018-09-03 18:24:51      阅读:757      评论:0      收藏:0      [点我收藏+]

标签:aggregate   product   app   group   desc   project   push   cdb   substr   

  1 package com.tangzhe.mongodb.mongotemplate;
  2 
  3 import com.mongodb.BasicDBObject;
  4 import com.mongodb.DBObject;
  5 import com.tangzhe.mongodb.BaseTest;
  6 import com.tangzhe.mongodb.Student;
  7 import com.tangzhe.shop.document.MBalanceIncrease;
  8 import com.tangzhe.shop.document.MVip;
  9 import com.tangzhe.shop.entity.AmountChart;
 10 import com.tangzhe.shop.entity.VipChart;
 11 import com.tangzhe.test.document.PlayareaStatistics;
 12 import com.tangzhe.test.util.DateUtils;
 13 import org.junit.Test;
 14 import org.springframework.beans.factory.annotation.Autowired;
 15 import org.springframework.data.domain.Sort;
 16 import org.springframework.data.mongodb.core.MongoTemplate;
 17 import org.springframework.data.mongodb.core.aggregation.Aggregation;
 18 import org.springframework.data.mongodb.core.aggregation.AggregationResults;
 19 import org.springframework.data.mongodb.core.query.Criteria;
 20 import org.springframework.data.mongodb.core.query.Query;
 21 
 22 import java.math.BigDecimal;
 23 import java.text.DecimalFormat;
 24 import java.text.ParseException;
 25 import java.text.SimpleDateFormat;
 26 import java.time.Duration;
 27 import java.time.Instant;
 28 import java.util.*;
 29 
 30 import static org.springframework.data.mongodb.core.aggregation.Aggregation.*;
 31 
 32 public class MongoTemplateTest2 extends BaseTest {
 33 
 34     @Autowired
 35     private MongoTemplate mongoTemplate;
 36 
 37     //@Test
 38     public void test01() {
 39 //        List<PlayareaStatistics> list = mongoTemplate.find(
 40 //                Query.query(
 41 //                        new Criteria().andOperator(
 42 //                                Criteria.where("areaId").is(21),
 43 //                                Criteria.where("type").is("READ")
 44 //                        )
 45 //                ),
 46 //                PlayareaStatistics.class);
 47 //        System.out.println(list);
 48 
 49 //        GroupByResults<PlayareaStatistics> group = mongoTemplate.group(
 50 //                Criteria.where("areaId").is(21),
 51 //                "playarea_statistics",
 52 //                new GroupBy("type"),
 53 //                PlayareaStatistics.class);
 54 //        System.out.println(group);
 55 
 56         Aggregation aggregation = Aggregation.newAggregation(
 57                 match(Criteria.where("areaId").is(21)),
 58                 group("type").count().as("sum"));
 59         AggregationResults<BasicDBObject> outputTypeCount =
 60                 mongoTemplate.aggregate(aggregation, PlayareaStatistics.class, BasicDBObject.class);
 61 
 62         for (Iterator<BasicDBObject> iterator = outputTypeCount.iterator(); iterator.hasNext(); ) {
 63             DBObject obj = iterator.next();
 64             System.out.println(obj);
 65         }
 66     }
 67 
 68     //@Test
 69     public void test02() {
 70         Aggregation aggregation = Aggregation.newAggregation(
 71                 match(
 72                         Criteria.where("areaId").is(21)
 73                                 .andOperator(Criteria.where("type").is("READ"))),
 74                 group("city").count().as("sum"));
 75         AggregationResults<BasicDBObject> outputTypeCount =
 76                 mongoTemplate.aggregate(aggregation, PlayareaStatistics.class, BasicDBObject.class);
 77 
 78         for (Iterator<BasicDBObject> iterator = outputTypeCount.iterator(); iterator.hasNext(); ) {
 79             DBObject obj = iterator.next();
 80             System.out.println(obj);
 81         }
 82     }
 83 
 84     //@Test
 85     public void test03() throws ParseException {
 86         // 默认查当月第一天至当天之间的数据
 87         //Date date = new Date();
 88         SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
 89         Date date = sdf.parse("2018-05-02 00:00:00");
 90         String beginTime = DateUtils.getMonthFirstDay(date);
 91         String endTime = DateUtils.getMonthLastDay(date);
 92         Date beginDate = sdf.parse(beginTime);
 93         Date endDate = sdf.parse(endTime);
 94 
 95         Aggregation aggregation = Aggregation.newAggregation(
 96                 match(
 97                         Criteria.where("areaId").is(21L)
 98                                 .andOperator(
 99                                         Criteria.where("operateTime").gte(beginDate).lt(endDate),
100                                         Criteria.where("type").is("READ"))),
101                 group("logDate").count().as("sum"));
102         AggregationResults<BasicDBObject> outputTypeCount =
103                 mongoTemplate.aggregate(aggregation, PlayareaStatistics.class, BasicDBObject.class);
104 
105         Map<String, Integer> map = new HashMap<>();
106         for (Iterator<BasicDBObject> iterator = outputTypeCount.iterator(); iterator.hasNext(); ) {
107             DBObject obj = iterator.next();
108             String day = ((String) obj.get("_id")).substring(8, 10); // day
109             map.put(day, (Integer) obj.get("sum"));
110         }
111 
112         System.out.println(map);
113     }
114 
115     //@Test
116     public void test04() throws ParseException {
117         SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
118         Date date = sdf.parse("2018-05-02 00:00:00");
119         String beginTime = DateUtils.getMonthFirstDay(date);
120         String endTime = DateUtils.getMonthLastDay(date);
121         Date beginDate = sdf.parse(beginTime);
122         Date endDate = sdf.parse(endTime);
123     }
124 
125     @Test
126     public void test05() throws ParseException {
127         Date date = new Date();
128         String today = DateUtils.formatToString(date, "yyyy-MM-dd");
129         String thisMonth = DateUtils.formatToString(date, "yyyy-MM");
130         List<MVip> list = mongoTemplate.find(
131                 Query.query(
132                         Criteria.where("day").is("2018-03-28")
133                 ), MVip.class);
134         System.out.println(list.size());
135     }
136 
137     @Test
138     public void test06() {
139         Date date = new Date();
140         String today = DateUtils.formatToString(date, "yyyy-MM-dd");
141         String thisMonth = DateUtils.formatToString(date, "yyyy-MM");
142         Double sum = 0.0;
143         List<MBalanceIncrease> list = mongoTemplate.find(
144                 Query.query(
145                         Criteria.where("day").is("2018-03-28")
146                 ), MBalanceIncrease.class);
147         for (MBalanceIncrease balance : list) {
148             sum = new BigDecimal(sum).add(new BigDecimal(balance.getAmount().toString())).doubleValue();
149         }
150 
151         DecimalFormat decimalFormat = new DecimalFormat("#.00");
152         sum = Double.valueOf(decimalFormat.format(sum));
153         System.out.println(sum);
154     }
155 
156     @Test
157     public void test07() {
158         Date date = new Date();
159         String today = DateUtils.formatToString(date, "yyyy-MM-dd");
160         String thisMonth = DateUtils.formatToString(date, "yyyy-MM");
161         Double sum = 0.0;
162         Aggregation aggregation = Aggregation.newAggregation(
163                 match(
164                         Criteria.where("day").in(DateUtils.getPast7Date())),
165                 group("day")
166                         .sum("amount").as("total")
167                         //.push("createDate").as("date")
168                         .first("day").as("day"),
169                 project("total", "day"),
170                 sort(Sort.Direction.DESC, "day"));
171         AggregationResults<BasicDBObject> outputTypeCount =
172                 mongoTemplate.aggregate(aggregation, MBalanceIncrease.class, BasicDBObject.class);
173 
174         for (Iterator<BasicDBObject> iterator = outputTypeCount.iterator(); iterator.hasNext(); ) {
175             DBObject obj = iterator.next();
176             System.out.println(obj);
177         }
178     }
179 
180     @Test
181     public void test08() {
182         Aggregation aggregation = Aggregation.newAggregation(
183                 match(Criteria.where("day").is("2018-08-16")),
184                 group("day").sum("amount").as("total"));
185         AggregationResults<BasicDBObject> result =
186                 mongoTemplate.aggregate(aggregation, MBalanceIncrease.class, BasicDBObject.class);
187 
188         System.out.println(result.getMappedResults().get(0).get("total"));
189     }
190 
191     @Test
192     public void test09() {
193         List<String> past7Date = DateUtils.getPast7Date();
194         Aggregation aggregation = Aggregation.newAggregation(
195                 match(
196                         Criteria.where("day").in(past7Date)),
197                 group("day")
198                         .sum("amount").as("total")
199                         .first("day").as("day"),
200                 project("total", "day"),
201                 sort(Sort.Direction.DESC, "day"));
202         AggregationResults<BasicDBObject> result =
203                 mongoTemplate.aggregate(aggregation, MBalanceIncrease.class, BasicDBObject.class);
204 
205         List<AmountChart> sevenDays = new ArrayList<>();
206         Map<String, Double> map = new HashMap<>();
207         for (Iterator<BasicDBObject> iterator = result.iterator(); iterator.hasNext(); ) {
208             DBObject obj = iterator.next();
209             map.put(obj.get("day").toString(), Double.valueOf(obj.get("total").toString()));
210         }
211 
212         for (String day : past7Date) {
213             if (map.containsKey(day)) {
214                 sevenDays.add(new AmountChart(day, map.get(day)));
215             } else {
216                 sevenDays.add(new AmountChart(day, 0.0));
217             }
218         }
219 
220         System.out.println(sevenDays);
221         AmountChart amountChart = sevenDays.get(0);
222         System.out.println(amountChart);
223     }
224 
225     @Test
226     public void test10() {
227         List<String> past6Months = DateUtils.getPast6Months();
228         Aggregation aggregation = Aggregation.newAggregation(
229                 match(
230                         Criteria.where("month").in(past6Months)),
231                 group("month")
232                         .sum("amount").as("total")
233                         .first("month").as("month"),
234                 project("total", "month"),
235                 sort(Sort.Direction.DESC, "month"));
236         AggregationResults<BasicDBObject> result =
237                 mongoTemplate.aggregate(aggregation, MBalanceIncrease.class, BasicDBObject.class);
238 
239         List<AmountChart> sixMonths = new ArrayList<>();
240         Map<String, Double> map = new HashMap<>();
241         for (Iterator<BasicDBObject> iterator = result.iterator(); iterator.hasNext(); ) {
242             DBObject obj = iterator.next();
243             map.put(obj.get("month").toString(), Double.valueOf(obj.get("total").toString()));
244         }
245 
246         for (String month : past6Months) {
247             if (map.containsKey(month)) {
248                 sixMonths.add(new AmountChart(month, map.get(month)));
249             } else {
250                 sixMonths.add(new AmountChart(month, 0.0));
251             }
252         }
253 
254         System.out.println(sixMonths);
255         AmountChart monthAmount = sixMonths.get(0);
256         System.out.println(monthAmount);
257     }
258 
259     @Test
260     public void test11() {
261         Aggregation aggregation = Aggregation.newAggregation(
262                 match(
263                         Criteria.where("province").is("江苏")),
264                 group("province").sum("amount").as("total"));
265         AggregationResults<BasicDBObject> result =
266                 mongoTemplate.aggregate(aggregation, com.tangzhe.shop.service.MOrder.class, BasicDBObject.class);
267 
268         System.out.println(result.getMappedResults().get(0).get("total"));
269     }
270 
271     @Test
272     public void test12() {
273         // 查询当日 老方法
274         List<MVip> list = mongoTemplate.find(
275                 Query.query(
276                         Criteria.where("province").is("江苏").and("day").is("2018-08-16")
277                 ), MVip.class);
278         System.out.println(list.size());
279 
280         // 查询当日 新方法
281         Aggregation aggregation = Aggregation.newAggregation(
282                 match(
283                         Criteria.where("province").is("江苏").and("day").is("2018-08-16")),
284                 group("province").count().as("total"));
285         AggregationResults<BasicDBObject> result =
286                 mongoTemplate.aggregate(aggregation, MVip.class, BasicDBObject.class);
287 
288         for (Iterator<BasicDBObject> iterator = result.iterator(); iterator.hasNext(); ) {
289             DBObject obj = iterator.next();
290             System.out.println(obj);
291         }
292         System.out.println(result.getMappedResults().get(0).get("total"));
293     }
294 
295     @Test
296     public void test13() {
297         // 查询近7日 老方法
298         List<VipChart> sevenDays = new ArrayList<>();
299         List<String> past6Date = DateUtils.getPast7Date();
300         for (String day : past6Date) {
301             int dc = mongoTemplate.find(
302                     Query.query(
303                             Criteria.where("province").is("江苏").and("day").is(day)
304                     ), MVip.class).size();
305             VipChart vipChart = new VipChart(day, dc);
306             sevenDays.add(vipChart);
307         }
308         sevenDays.forEach(System.out::println);
309 
310         // 查询近7日 新方法
311         List<String> past7Date = DateUtils.getPast7Date();
312         Aggregation aggregation = Aggregation.newAggregation(
313                 match(
314                         Criteria.where("province").is("江苏").and("day").in(past7Date)),
315                 group("day")
316                         .count().as("total")
317                         .first("day").as("day"),
318                 project("total", "day"),
319                 sort(Sort.Direction.DESC, "day"));
320         AggregationResults<BasicDBObject> result =
321                 mongoTemplate.aggregate(aggregation, MVip.class, BasicDBObject.class);
322 
323         for (Iterator<BasicDBObject> iterator = result.iterator(); iterator.hasNext(); ) {
324             DBObject obj = iterator.next();
325             System.out.println(obj);
326         }
327     }
328 
329     @Test
330     public void test14() {
331         // 查询累计 老方法
332         int total = mongoTemplate.find(
333                 Query.query(
334                         Criteria.where("city").is("苏州")
335                 ), MVip.class).size();
336         System.out.println(total);
337 
338         // 查询累计 新方法
339         Aggregation aggregation = Aggregation.newAggregation(
340                 match(
341                         Criteria.where("city").is("苏州")),
342                 group("province").count().as("total"));
343         AggregationResults<BasicDBObject> result = mongoTemplate.aggregate(aggregation, MVip.class, BasicDBObject.class);
344         total = Integer.valueOf(result.getMappedResults().get(0).get("total").toString());
345         System.out.println(total);
346     }
347 
348     @Test
349     public void test15() {
350         Map<String, Integer> map = new HashMap<>();
351         Aggregation aggregation = Aggregation.newAggregation(
352                 match(
353                         Criteria.where("province").is("江苏")),
354                 group("city").count().as("total"));
355         AggregationResults<BasicDBObject> result = mongoTemplate.aggregate(aggregation, MVip.class, BasicDBObject.class);
356         for (Iterator<BasicDBObject> iterator = result.iterator(); iterator.hasNext(); ) {
357             DBObject obj = iterator.next();
358             System.out.println(obj);
359             map.put(obj.get("_id").toString(), Integer.valueOf(obj.get("total").toString()));
360         }
361         System.out.println();
362     }
363 
364     /**
365      * 关联查询
366      */
367     @Test
368     public void test16() {
369         Instant start = Instant.now();
370         Aggregation aggregation = Aggregation.newAggregation(
371                 match(
372                         Criteria.where("id").is("5b7a5fa1d0c5852d745c4e81")),
373                         lookup("class_info", "classId", "_id", "class_info")
374                 );
375         AggregationResults<BasicDBObject> result = mongoTemplate.aggregate(aggregation, Student.class, BasicDBObject.class);
376         for (Iterator<BasicDBObject> iterator = result.iterator(); iterator.hasNext(); ) {
377             DBObject obj = iterator.next();
378             System.out.println(obj);
379         }
380         Instant end = Instant.now();
381         System.out.println(Duration.between(start, end).toMillis());
382     }
383 
384     @Test
385     public void test17() {
386         Aggregation aggregation = Aggregation.newAggregation(
387                 match(Criteria.where("province").is("江苏")),
388                 group("userId").count().as("total").push("city").as("city"),
389                 match(Criteria.where("total").gte(2)),
390                 project("total", "city"));
391         AggregationResults<BasicDBObject> result = mongoTemplate.aggregate(aggregation, MCustomerSave.class, BasicDBObject.class);
392         int total = result.getMappedResults().size();
393         System.out.println(total);
394     }
395 
396     @Test
397     public void test18() {
398         Map<String, Integer> map = new HashMap<>();
399         Aggregation aggregation = Aggregation.newAggregation(
400                 match(Criteria.where("province").is("江苏")),
401                 group("city").count().as("total"));
402         AggregationResults<BasicDBObject> result = mongoTemplate.aggregate(aggregation, MCustomerSave.class, BasicDBObject.class);
403         for (Iterator<BasicDBObject> iterator = result.iterator(); iterator.hasNext(); ) {
404             DBObject obj = iterator.next();
405             String city = obj.get("_id").toString();
406             aggregation = Aggregation.newAggregation(
407                     match(Criteria.where("city").is(city)),
408                     group("userId").count().as("total"),
409                     match(Criteria.where("total").gte(2)));
410             AggregationResults<BasicDBObject> res = mongoTemplate.aggregate(aggregation, MCustomerSave.class, BasicDBObject.class);
411             map.put(city, res.getMappedResults().size());
412         }
413         System.out.println();
414     }
415 
416 }

 

  1 package com.tangzhe.mongodb.mongotemplate;
  2 
  3 import com.mongodb.BasicDBObject;
  4 import com.mongodb.DBObject;
  5 import com.tangzhe.mongodb.BaseTest;
  6 import com.tangzhe.shop.document.MOrder;
  7 import com.tangzhe.shop.document.MUser;
  8 import com.tangzhe.shop.document.MVipRecord;
  9 import com.tangzhe.shop.service.Product;
 10 import com.tangzhe.test.util.DateUtils;
 11 import org.bson.types.Decimal128;
 12 import org.junit.Test;
 13 import org.springframework.beans.factory.annotation.Autowired;
 14 import org.springframework.data.domain.Sort;
 15 import org.springframework.data.mongodb.core.MongoTemplate;
 16 import org.springframework.data.mongodb.core.aggregation.Aggregation;
 17 import org.springframework.data.mongodb.core.aggregation.AggregationResults;
 18 import org.springframework.data.mongodb.core.query.Criteria;
 19 
 20 import java.math.BigDecimal;
 21 import java.time.Duration;
 22 import java.time.Instant;
 23 import java.util.*;
 24 
 25 import static org.springframework.data.mongodb.core.aggregation.Aggregation.*;
 26 
 27 public class ShopTest extends BaseTest {
 28 
 29     @Autowired
 30     private MongoTemplate mongoTemplate;
 31 
 32     /**
 33      * 一共获取了多少食堂劵
 34      */
 35     @Test
 36     public void test01() {
 37         Instant start = Instant.now();
 38 
 39         Aggregation aggregation = Aggregation.newAggregation(
 40                 match(Criteria.where("userId").is(8744L)),
 41                 unwind("productList"),
 42                 group("userId").sum("productList.ticket").as("total"));
 43         AggregationResults<BasicDBObject> result =
 44                 mongoTemplate.aggregate(aggregation, MOrder.class, BasicDBObject.class);
 45         System.out.println(result.getMappedResults().get(0).get("total"));
 46 
 47         Instant end = Instant.now();
 48         System.out.println(Duration.between(start, end).toMillis());
 49     }
 50 
 51     /**
 52      * 一共节约了多少钱
 53      */
 54     @Test
 55     public void test02() {
 56         Instant start = Instant.now();
 57 
 58         Aggregation aggregation = Aggregation.newAggregation(
 59                 match(Criteria.where("userId").is(8744L)),
 60                 group("userId")
 61                         .sum("orgAmount").as("orgAmount")
 62                         .sum("payAmount").as("payAmount"),
 63                 project("orgAmount", "payAmount")
 64                         .and("orgAmount").minus("payAmount").as("saveAmount"));
 65         AggregationResults<BasicDBObject> result = mongoTemplate.aggregate(aggregation, MOrder.class, BasicDBObject.class);
 66 
 67         BigDecimal saveAmount = ((Decimal128)result.getMappedResults().get(0).get("saveAmount")).bigDecimalValue();
 68         System.out.println(saveAmount);
 69 
 70         Instant end = Instant.now();
 71         System.out.println(Duration.between(start, end).toMillis());
 72     }
 73 
 74     /**
 75      *  一共支付了多少钱
 76      */
 77     @Test
 78     public void test03() {
 79         Instant start = Instant.now();
 80 
 81         Aggregation aggregation = Aggregation.newAggregation(
 82                 match(Criteria.where("userId").is(8744L)),
 83                 group("userId").sum("payAmount").as("total"));
 84         AggregationResults<BasicDBObject> result =
 85                 mongoTemplate.aggregate(aggregation, MOrder.class, BasicDBObject.class);
 86 
 87         System.out.println(result.getMappedResults().get(0).get("total"));
 88 
 89         Instant end = Instant.now();
 90         System.out.println(Duration.between(start, end).toMillis());
 91     }
 92 
 93     /**
 94      * 下单总共原始价多少钱
 95      */
 96     @Test
 97     public void test04() {
 98         Aggregation aggregation = Aggregation.newAggregation(
 99                 match(Criteria.where("userId").is(8744L)),
100                 group("userId").sum("orgAmount").as("total"));
101         AggregationResults<BasicDBObject> result = mongoTemplate.aggregate(aggregation, MOrder.class, BasicDBObject.class);
102 
103         BigDecimal orgAmount = ((Decimal128) result.getMappedResults().get(0).get("total")).bigDecimalValue();
104         System.out.println(orgAmount);
105     }
106 
107     /**
108      * 交易的产品比例(含产品类型和比例)
109      */
110     @Test
111     public void test05() {
112         Instant start = Instant.now();
113 
114         Aggregation aggregation = Aggregation.newAggregation(
115                 match(Criteria.where("userId").is(8744L)),
116                 project("productList"));
117         AggregationResults<BasicDBObject> result = mongoTemplate.aggregate(aggregation, MOrder.class, BasicDBObject.class);
118 
119         int sum = 0;
120         for (Iterator<BasicDBObject> iterator = result.iterator(); iterator.hasNext(); ) {
121             DBObject obj = iterator.next();
122             List<Product> products = (List<Product>) obj.get("productList");
123             sum += products.size();
124         }
125 
126         aggregation = Aggregation.newAggregation(
127                 match(Criteria.where("userId").is(8744L)),
128                 unwind("productList"),
129                 group("productList.productType").count().as("total"));
130         result = mongoTemplate.aggregate(aggregation, MOrder.class, BasicDBObject.class);
131 
132         Map<String, BigDecimal> rateMap = new HashMap<>();
133         int i = 0;
134         BigDecimal other = new BigDecimal(0);
135         for (Iterator<BasicDBObject> iterator = result.iterator(); iterator.hasNext(); ) {
136             DBObject obj = iterator.next();
137             if (i == 6) {
138                 rateMap.put((String)obj.get("_id"), new BigDecimal(1).subtract(other));
139                 break;
140             }
141             BigDecimal rate = new BigDecimal((int)obj.get("total")).divide(new BigDecimal(sum));
142             rateMap.put((String)obj.get("_id"), rate);
143             other = other.add(rate);
144             i ++;
145         }
146 
147         Instant end = Instant.now();
148         System.out.println(Duration.between(start, end).toMillis());
149     }
150 
151     /**
152      * 一共下了多少单
153      */
154     @Test
155     public void test06() {
156         Aggregation aggregation = Aggregation.newAggregation(
157                 match(Criteria.where("userId").is(8744L)),
158                 group("userId").count().as("count"));
159         AggregationResults<BasicDBObject> result =
160                 mongoTemplate.aggregate(aggregation, MOrder.class, BasicDBObject.class);
161 
162         int count = (int) result.getMappedResults().get(0).get("count");
163         System.out.println(count);
164     }
165 
166     /**
167      * 最喜欢的店铺(即下单最多的店铺)
168      */
169     @Test
170     public void test07() {
171         Aggregation aggregation = Aggregation.newAggregation(
172                 match(Criteria.where("userId").is(8744L)),
173                 group("shopId").count().as("count"),
174                 sort(Sort.Direction.DESC, "count"),
175                 limit(1));
176         AggregationResults<BasicDBObject> result =
177                 mongoTemplate.aggregate(aggregation, MOrder.class, BasicDBObject.class);
178 
179         long shopId = (long) result.getMappedResults().get(0).get("_id");
180         int count = (int) result.getMappedResults().get(0).get("count");
181         System.out.println(shopId);
182         System.out.println(count);
183     }
184 
185     /**
186      * 下单最多的那天和下单数量
187      */
188     @Test
189     public void test08() {
190         Aggregation aggregation = Aggregation.newAggregation(
191                 match(Criteria.where("userId").is(8744L)),
192                 project().andExpression("{$dateToString:{format:‘%Y-%m-%d‘,date: ‘$createTime‘}}").as("createTime"),
193                 group("createTime").count().as("count"),
194                 sort(Sort.Direction.DESC, "count"),
195                 limit(1));
196         AggregationResults<BasicDBObject> result =
197                 mongoTemplate.aggregate(aggregation, MOrder.class, BasicDBObject.class);
198         String day = (String) result.getMappedResults().get(0).get("_id");
199         int count = (int) result.getMappedResults().get(0).get("count");
200         System.out.println(day);
201         System.out.println(count);
202     }
203 
204     /**
205      * 花费金额最多的那天和金额
206      */
207     @Test
208     public void test09() {
209         Aggregation aggregation = Aggregation.newAggregation(
210                 match(Criteria.where("userId").is(8744L)
211                         .and("createTime").gte(DateUtils.fromString("2018-01-01 16:00:57", "yyyy-MM-dd HH:mm:ss")).lte(new Date())),
212                 project("payAmount").andExpression("{$dateToString:{format:‘%Y-%m-%d‘,date: ‘$createTime‘}}").as("createTime"),
213                 group("createTime").sum("payAmount").as("total"),
214                 sort(Sort.Direction.DESC, "total"),
215                 limit(1));
216         AggregationResults<BasicDBObject> result =
217                 mongoTemplate.aggregate(aggregation, MOrder.class, BasicDBObject.class);
218         String day = (String) result.getMappedResults().get(0).get("_id");
219         BigDecimal amount = ((Decimal128)result.getMappedResults().get(0).get("total")).bigDecimalValue();
220         System.out.println(day);
221         System.out.println(amount);
222     }
223 
224     /**
225      * 前3笔最多消费
226      */
227     @Test
228     public void test10() {
229         Aggregation aggregation = Aggregation.newAggregation(
230                 match(Criteria.where("userId").is(8744L)),
231                 sort(Sort.Direction.DESC, "payAmount"),
232                 limit(3));
233         AggregationResults<BasicDBObject> result = mongoTemplate.aggregate(aggregation, MOrder.class, BasicDBObject.class);
234 
235         List<MOrder> orders = new ArrayList<>(3);
236 
237         for (BasicDBObject bd : result.getMappedResults()) {
238             MOrder order = new MOrder();
239             order.setOrderId(bd.getString("orderId"));
240             order.setPayAmount((Decimal128) bd.get("payAmount"));
241             order.setShopId(bd.getLong("shopId"));
242             order.setCreateTime(bd.getDate("createTime"));
243             orders.add(order);
244         }
245         System.out.println(orders);
246     }
247 
248     /**
249      * 第一笔交易信息
250      */
251     @Test
252     public void test11() {
253         Aggregation aggregation = Aggregation.newAggregation(
254                 match(Criteria.where("userId").is(8744L)),
255                 sort(Sort.Direction.ASC, "createTime"),
256                 limit(1));
257         AggregationResults<BasicDBObject> result = mongoTemplate.aggregate(aggregation, MOrder.class, BasicDBObject.class);
258         BasicDBObject bd = result.getMappedResults().get(0);
259         MOrder order = new MOrder();
260         order.setOrderId(bd.getString("orderId"));
261         order.setPayAmount((Decimal128) bd.get("payAmount"));
262         order.setShopId(bd.getLong("shopId"));
263         order.setCreateTime(bd.getDate("createTime"));
264         System.out.println("第一笔交易时间为 " + DateUtils.formatToString(order.getCreateTime(), "yyyy-MM-dd HH:mm:ss"));
265         System.out.println("第一笔交易金额为 " + order.getPayAmount().bigDecimalValue().setScale(2, BigDecimal.ROUND_HALF_DOWN));
266         System.out.println("第一笔交易商家id为 " + order.getShopId());
267         System.out.println("第一笔交易订单号为 " + order.getOrderId());
268     }
269 
270     /**
271      * 查询成为会员的时间和第几位会员
272      */
273     @Test
274     public void test12() {
275         Long userId = 1L;
276 
277         Aggregation agg = Aggregation.newAggregation(
278                 match(
279                         Criteria.where("userId").is(userId)
280                                 .and("afterUserType").is("FORMAL_VIP")),
281                 sort(Sort.Direction.ASC, "startTime"),
282                 limit(1));
283         AggregationResults<BasicDBObject> result1 = mongoTemplate.aggregate(agg, MVipRecord.class, BasicDBObject.class);
284 
285         agg = Aggregation.newAggregation(
286                 match(
287                         Criteria.where("startTime")
288                                 .lt(result1.getMappedResults().get(0).getDate("startTime"))));
289         AggregationResults<BasicDBObject> result2 = mongoTemplate.aggregate(agg, MVipRecord.class, BasicDBObject.class);
290         int count = result2.getMappedResults().size() + 1;
291         System.out.println("您成为会员的时间:" + DateUtils.formatToString(result1.getMappedResults().get(0).getDate("startTime"), "yyyy-MM-dd hh:mm:ss"));
292         System.out.println("您是第" + count + "位会员");
293     }
294 
295     /**
296      * 查询注册时间和是第几位用户
297      */
298     @Test
299     public void test13() {
300         Instant start = Instant.now();
301         Long userId = 1L;
302         Aggregation agg = Aggregation.newAggregation(
303                 match(Criteria.where("userId").is(userId)));
304         AggregationResults<BasicDBObject> result1 = mongoTemplate.aggregate(agg, MUser.class, BasicDBObject.class);
305         agg = Aggregation.newAggregation(
306                 match(
307                         Criteria.where("createTime")
308                                 .lt(result1.getMappedResults().get(0).getDate("createTime"))),
309                 project("userId"));
310         AggregationResults<BasicDBObject> result2 = mongoTemplate.aggregate(agg, MUser.class, BasicDBObject.class);
311         int count = result2.getMappedResults().size() + 1;
312         System.out.println("您成为用户的时间:" + DateUtils.formatToString(result1.getMappedResults().get(0).getDate("createTime"), "yyyy-MM-dd hh:mm:ss"));
313         System.out.println("您是第" + count + "位注册用户");
314         Instant end = Instant.now();
315         System.out.println(Duration.between(start, end).toMillis());
316     }
317 
318 }

 

mongoTemplate聚合操作Demo

标签:aggregate   product   app   group   desc   project   push   cdb   substr   

原文地址:https://www.cnblogs.com/tangzhe/p/9579908.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!