mongoTemplate聚合操作Demo
package com.tangzhe.mongodb.mongotemplate; import com.mongodb.BasicDBObject;
import com.mongodb.DBObject;
import com.tangzhe.mongodb.BaseTest;
import com.tangzhe.mongodb.Student;
import com.tangzhe.shop.document.MBalanceIncrease;
import com.tangzhe.shop.document.MVip;
import com.tangzhe.shop.entity.AmountChart;
import com.tangzhe.shop.entity.VipChart;
import com.tangzhe.test.document.PlayareaStatistics;
import com.tangzhe.test.util.DateUtils;
import org.junit.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.aggregation.Aggregation;
import org.springframework.data.mongodb.core.aggregation.AggregationResults;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query; import java.math.BigDecimal;
import java.text.DecimalFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.Duration;
import java.time.Instant;
import java.util.*; import static org.springframework.data.mongodb.core.aggregation.Aggregation.*; public class MongoTemplateTest2 extends BaseTest { @Autowired
private MongoTemplate mongoTemplate; //@Test
public void test01() {
// List<PlayareaStatistics> list = mongoTemplate.find(
// Query.query(
// new Criteria().andOperator(
// Criteria.where("areaId").is(21),
// Criteria.where("type").is("READ")
// )
// ),
// PlayareaStatistics.class);
// System.out.println(list); // GroupByResults<PlayareaStatistics> group = mongoTemplate.group(
// Criteria.where("areaId").is(21),
// "playarea_statistics",
// new GroupBy("type"),
// PlayareaStatistics.class);
// System.out.println(group); Aggregation aggregation = Aggregation.newAggregation(
match(Criteria.where("areaId").is(21)),
group("type").count().as("sum"));
AggregationResults<BasicDBObject> outputTypeCount =
mongoTemplate.aggregate(aggregation, PlayareaStatistics.class, BasicDBObject.class); for (Iterator<BasicDBObject> iterator = outputTypeCount.iterator(); iterator.hasNext(); ) {
DBObject obj = iterator.next();
System.out.println(obj);
}
} //@Test
public void test02() {
Aggregation aggregation = Aggregation.newAggregation(
match(
Criteria.where("areaId").is(21)
.andOperator(Criteria.where("type").is("READ"))),
group("city").count().as("sum"));
AggregationResults<BasicDBObject> outputTypeCount =
mongoTemplate.aggregate(aggregation, PlayareaStatistics.class, BasicDBObject.class); for (Iterator<BasicDBObject> iterator = outputTypeCount.iterator(); iterator.hasNext(); ) {
DBObject obj = iterator.next();
System.out.println(obj);
}
} //@Test
public void test03() throws ParseException {
// 默认查当月第一天至当天之间的数据
//Date date = new Date();
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
Date date = sdf.parse("2018-05-02 00:00:00");
String beginTime = DateUtils.getMonthFirstDay(date);
String endTime = DateUtils.getMonthLastDay(date);
Date beginDate = sdf.parse(beginTime);
Date endDate = sdf.parse(endTime); Aggregation aggregation = Aggregation.newAggregation(
match(
Criteria.where("areaId").is(21L)
.andOperator(
Criteria.where("operateTime").gte(beginDate).lt(endDate),
Criteria.where("type").is("READ"))),
group("logDate").count().as("sum"));
AggregationResults<BasicDBObject> outputTypeCount =
mongoTemplate.aggregate(aggregation, PlayareaStatistics.class, BasicDBObject.class); Map<String, Integer> map = new HashMap<>();
for (Iterator<BasicDBObject> iterator = outputTypeCount.iterator(); iterator.hasNext(); ) {
DBObject obj = iterator.next();
String day = ((String) obj.get("_id")).substring(8, 10); // day
map.put(day, (Integer) obj.get("sum"));
} System.out.println(map);
} //@Test
public void test04() throws ParseException {
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
Date date = sdf.parse("2018-05-02 00:00:00");
String beginTime = DateUtils.getMonthFirstDay(date);
String endTime = DateUtils.getMonthLastDay(date);
Date beginDate = sdf.parse(beginTime);
Date endDate = sdf.parse(endTime);
} @Test
public void test05() throws ParseException {
Date date = new Date();
String today = DateUtils.formatToString(date, "yyyy-MM-dd");
String thisMonth = DateUtils.formatToString(date, "yyyy-MM");
List<MVip> list = mongoTemplate.find(
Query.query(
Criteria.where("day").is("2018-03-28")
), MVip.class);
System.out.println(list.size());
} @Test
public void test06() {
Date date = new Date();
String today = DateUtils.formatToString(date, "yyyy-MM-dd");
String thisMonth = DateUtils.formatToString(date, "yyyy-MM");
Double sum = 0.0;
List<MBalanceIncrease> list = mongoTemplate.find(
Query.query(
Criteria.where("day").is("2018-03-28")
), MBalanceIncrease.class);
for (MBalanceIncrease balance : list) {
sum = new BigDecimal(sum).add(new BigDecimal(balance.getAmount().toString())).doubleValue();
} DecimalFormat decimalFormat = new DecimalFormat("#.00");
sum = Double.valueOf(decimalFormat.format(sum));
System.out.println(sum);
} @Test
public void test07() {
Date date = new Date();
String today = DateUtils.formatToString(date, "yyyy-MM-dd");
String thisMonth = DateUtils.formatToString(date, "yyyy-MM");
Double sum = 0.0;
Aggregation aggregation = Aggregation.newAggregation(
match(
Criteria.where("day").in(DateUtils.getPast7Date())),
group("day")
.sum("amount").as("total")
//.push("createDate").as("date")
.first("day").as("day"),
project("total", "day"),
sort(Sort.Direction.DESC, "day"));
AggregationResults<BasicDBObject> outputTypeCount =
mongoTemplate.aggregate(aggregation, MBalanceIncrease.class, BasicDBObject.class); for (Iterator<BasicDBObject> iterator = outputTypeCount.iterator(); iterator.hasNext(); ) {
DBObject obj = iterator.next();
System.out.println(obj);
}
} @Test
public void test08() {
Aggregation aggregation = Aggregation.newAggregation(
match(Criteria.where("day").is("2018-08-16")),
group("day").sum("amount").as("total"));
AggregationResults<BasicDBObject> result =
mongoTemplate.aggregate(aggregation, MBalanceIncrease.class, BasicDBObject.class); System.out.println(result.getMappedResults().get(0).get("total"));
} @Test
public void test09() {
List<String> past7Date = DateUtils.getPast7Date();
Aggregation aggregation = Aggregation.newAggregation(
match(
Criteria.where("day").in(past7Date)),
group("day")
.sum("amount").as("total")
.first("day").as("day"),
project("total", "day"),
sort(Sort.Direction.DESC, "day"));
AggregationResults<BasicDBObject> result =
mongoTemplate.aggregate(aggregation, MBalanceIncrease.class, BasicDBObject.class); List<AmountChart> sevenDays = new ArrayList<>();
Map<String, Double> map = new HashMap<>();
for (Iterator<BasicDBObject> iterator = result.iterator(); iterator.hasNext(); ) {
DBObject obj = iterator.next();
map.put(obj.get("day").toString(), Double.valueOf(obj.get("total").toString()));
} for (String day : past7Date) {
if (map.containsKey(day)) {
sevenDays.add(new AmountChart(day, map.get(day)));
} else {
sevenDays.add(new AmountChart(day, 0.0));
}
} System.out.println(sevenDays);
AmountChart amountChart = sevenDays.get(0);
System.out.println(amountChart);
} @Test
public void test10() {
List<String> past6Months = DateUtils.getPast6Months();
Aggregation aggregation = Aggregation.newAggregation(
match(
Criteria.where("month").in(past6Months)),
group("month")
.sum("amount").as("total")
.first("month").as("month"),
project("total", "month"),
sort(Sort.Direction.DESC, "month"));
AggregationResults<BasicDBObject> result =
mongoTemplate.aggregate(aggregation, MBalanceIncrease.class, BasicDBObject.class); List<AmountChart> sixMonths = new ArrayList<>();
Map<String, Double> map = new HashMap<>();
for (Iterator<BasicDBObject> iterator = result.iterator(); iterator.hasNext(); ) {
DBObject obj = iterator.next();
map.put(obj.get("month").toString(), Double.valueOf(obj.get("total").toString()));
} for (String month : past6Months) {
if (map.containsKey(month)) {
sixMonths.add(new AmountChart(month, map.get(month)));
} else {
sixMonths.add(new AmountChart(month, 0.0));
}
} System.out.println(sixMonths);
AmountChart monthAmount = sixMonths.get(0);
System.out.println(monthAmount);
} @Test
public void test11() {
Aggregation aggregation = Aggregation.newAggregation(
match(
Criteria.where("province").is("江苏")),
group("province").sum("amount").as("total"));
AggregationResults<BasicDBObject> result =
mongoTemplate.aggregate(aggregation, com.tangzhe.shop.service.MOrder.class, BasicDBObject.class); System.out.println(result.getMappedResults().get(0).get("total"));
} @Test
public void test12() {
// 查询当日 老方法
List<MVip> list = mongoTemplate.find(
Query.query(
Criteria.where("province").is("江苏").and("day").is("2018-08-16")
), MVip.class);
System.out.println(list.size()); // 查询当日 新方法
Aggregation aggregation = Aggregation.newAggregation(
match(
Criteria.where("province").is("江苏").and("day").is("2018-08-16")),
group("province").count().as("total"));
AggregationResults<BasicDBObject> result =
mongoTemplate.aggregate(aggregation, MVip.class, BasicDBObject.class); for (Iterator<BasicDBObject> iterator = result.iterator(); iterator.hasNext(); ) {
DBObject obj = iterator.next();
System.out.println(obj);
}
System.out.println(result.getMappedResults().get(0).get("total"));
} @Test
public void test13() {
// 查询近7日 老方法
List<VipChart> sevenDays = new ArrayList<>();
List<String> past6Date = DateUtils.getPast7Date();
for (String day : past6Date) {
int dc = mongoTemplate.find(
Query.query(
Criteria.where("province").is("江苏").and("day").is(day)
), MVip.class).size();
VipChart vipChart = new VipChart(day, dc);
sevenDays.add(vipChart);
}
sevenDays.forEach(System.out::println); // 查询近7日 新方法
List<String> past7Date = DateUtils.getPast7Date();
Aggregation aggregation = Aggregation.newAggregation(
match(
Criteria.where("province").is("江苏").and("day").in(past7Date)),
group("day")
.count().as("total")
.first("day").as("day"),
project("total", "day"),
sort(Sort.Direction.DESC, "day"));
AggregationResults<BasicDBObject> result =
mongoTemplate.aggregate(aggregation, MVip.class, BasicDBObject.class); for (Iterator<BasicDBObject> iterator = result.iterator(); iterator.hasNext(); ) {
DBObject obj = iterator.next();
System.out.println(obj);
}
} @Test
public void test14() {
// 查询累计 老方法
int total = mongoTemplate.find(
Query.query(
Criteria.where("city").is("苏州")
), MVip.class).size();
System.out.println(total); // 查询累计 新方法
Aggregation aggregation = Aggregation.newAggregation(
match(
Criteria.where("city").is("苏州")),
group("province").count().as("total"));
AggregationResults<BasicDBObject> result = mongoTemplate.aggregate(aggregation, MVip.class, BasicDBObject.class);
total = Integer.valueOf(result.getMappedResults().get(0).get("total").toString());
System.out.println(total);
} @Test
public void test15() {
Map<String, Integer> map = new HashMap<>();
Aggregation aggregation = Aggregation.newAggregation(
match(
Criteria.where("province").is("江苏")),
group("city").count().as("total"));
AggregationResults<BasicDBObject> result = mongoTemplate.aggregate(aggregation, MVip.class, BasicDBObject.class);
for (Iterator<BasicDBObject> iterator = result.iterator(); iterator.hasNext(); ) {
DBObject obj = iterator.next();
System.out.println(obj);
map.put(obj.get("_id").toString(), Integer.valueOf(obj.get("total").toString()));
}
System.out.println();
} /**
* 关联查询
*/
@Test
public void test16() {
Instant start = Instant.now();
Aggregation aggregation = Aggregation.newAggregation(
match(
Criteria.where("id").is("5b7a5fa1d0c5852d745c4e81")),
lookup("class_info", "classId", "_id", "class_info")
);
AggregationResults<BasicDBObject> result = mongoTemplate.aggregate(aggregation, Student.class, BasicDBObject.class);
for (Iterator<BasicDBObject> iterator = result.iterator(); iterator.hasNext(); ) {
DBObject obj = iterator.next();
System.out.println(obj);
}
Instant end = Instant.now();
System.out.println(Duration.between(start, end).toMillis());
} @Test
public void test17() {
Aggregation aggregation = Aggregation.newAggregation(
match(Criteria.where("province").is("江苏")),
group("userId").count().as("total").push("city").as("city"),
match(Criteria.where("total").gte(2)),
project("total", "city"));
AggregationResults<BasicDBObject> result = mongoTemplate.aggregate(aggregation, MCustomerSave.class, BasicDBObject.class);
int total = result.getMappedResults().size();
System.out.println(total);
} @Test
public void test18() {
Map<String, Integer> map = new HashMap<>();
Aggregation aggregation = Aggregation.newAggregation(
match(Criteria.where("province").is("江苏")),
group("city").count().as("total"));
AggregationResults<BasicDBObject> result = mongoTemplate.aggregate(aggregation, MCustomerSave.class, BasicDBObject.class);
for (Iterator<BasicDBObject> iterator = result.iterator(); iterator.hasNext(); ) {
DBObject obj = iterator.next();
String city = obj.get("_id").toString();
aggregation = Aggregation.newAggregation(
match(Criteria.where("city").is(city)),
group("userId").count().as("total"),
match(Criteria.where("total").gte(2)));
AggregationResults<BasicDBObject> res = mongoTemplate.aggregate(aggregation, MCustomerSave.class, BasicDBObject.class);
map.put(city, res.getMappedResults().size());
}
System.out.println();
} }
package com.tangzhe.mongodb.mongotemplate; import com.mongodb.BasicDBObject;
import com.mongodb.DBObject;
import com.tangzhe.mongodb.BaseTest;
import com.tangzhe.shop.document.MOrder;
import com.tangzhe.shop.document.MUser;
import com.tangzhe.shop.document.MVipRecord;
import com.tangzhe.shop.service.Product;
import com.tangzhe.test.util.DateUtils;
import org.bson.types.Decimal128;
import org.junit.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.aggregation.Aggregation;
import org.springframework.data.mongodb.core.aggregation.AggregationResults;
import org.springframework.data.mongodb.core.query.Criteria; import java.math.BigDecimal;
import java.time.Duration;
import java.time.Instant;
import java.util.*; import static org.springframework.data.mongodb.core.aggregation.Aggregation.*; public class ShopTest extends BaseTest { @Autowired
private MongoTemplate mongoTemplate; /**
* 一共获取了多少食堂劵
*/
@Test
public void test01() {
Instant start = Instant.now(); Aggregation aggregation = Aggregation.newAggregation(
match(Criteria.where("userId").is(8744L)),
unwind("productList"),
group("userId").sum("productList.ticket").as("total"));
AggregationResults<BasicDBObject> result =
mongoTemplate.aggregate(aggregation, MOrder.class, BasicDBObject.class);
System.out.println(result.getMappedResults().get(0).get("total")); Instant end = Instant.now();
System.out.println(Duration.between(start, end).toMillis());
} /**
* 一共节约了多少钱
*/
@Test
public void test02() {
Instant start = Instant.now(); Aggregation aggregation = Aggregation.newAggregation(
match(Criteria.where("userId").is(8744L)),
group("userId")
.sum("orgAmount").as("orgAmount")
.sum("payAmount").as("payAmount"),
project("orgAmount", "payAmount")
.and("orgAmount").minus("payAmount").as("saveAmount"));
AggregationResults<BasicDBObject> result = mongoTemplate.aggregate(aggregation, MOrder.class, BasicDBObject.class); BigDecimal saveAmount = ((Decimal128)result.getMappedResults().get(0).get("saveAmount")).bigDecimalValue();
System.out.println(saveAmount); Instant end = Instant.now();
System.out.println(Duration.between(start, end).toMillis());
} /**
* 一共支付了多少钱
*/
@Test
public void test03() {
Instant start = Instant.now(); Aggregation aggregation = Aggregation.newAggregation(
match(Criteria.where("userId").is(8744L)),
group("userId").sum("payAmount").as("total"));
AggregationResults<BasicDBObject> result =
mongoTemplate.aggregate(aggregation, MOrder.class, BasicDBObject.class); System.out.println(result.getMappedResults().get(0).get("total")); Instant end = Instant.now();
System.out.println(Duration.between(start, end).toMillis());
} /**
* 下单总共原始价多少钱
*/
@Test
public void test04() {
Aggregation aggregation = Aggregation.newAggregation(
match(Criteria.where("userId").is(8744L)),
group("userId").sum("orgAmount").as("total"));
AggregationResults<BasicDBObject> result = mongoTemplate.aggregate(aggregation, MOrder.class, BasicDBObject.class); BigDecimal orgAmount = ((Decimal128) result.getMappedResults().get(0).get("total")).bigDecimalValue();
System.out.println(orgAmount);
} /**
* 交易的产品比例(含产品类型和比例)
*/
@Test
public void test05() {
Instant start = Instant.now(); Aggregation aggregation = Aggregation.newAggregation(
match(Criteria.where("userId").is(8744L)),
project("productList"));
AggregationResults<BasicDBObject> result = mongoTemplate.aggregate(aggregation, MOrder.class, BasicDBObject.class); int sum = 0;
for (Iterator<BasicDBObject> iterator = result.iterator(); iterator.hasNext(); ) {
DBObject obj = iterator.next();
List<Product> products = (List<Product>) obj.get("productList");
sum += products.size();
} aggregation = Aggregation.newAggregation(
match(Criteria.where("userId").is(8744L)),
unwind("productList"),
group("productList.productType").count().as("total"));
result = mongoTemplate.aggregate(aggregation, MOrder.class, BasicDBObject.class); Map<String, BigDecimal> rateMap = new HashMap<>();
int i = 0;
BigDecimal other = new BigDecimal(0);
for (Iterator<BasicDBObject> iterator = result.iterator(); iterator.hasNext(); ) {
DBObject obj = iterator.next();
if (i == 6) {
rateMap.put((String)obj.get("_id"), new BigDecimal(1).subtract(other));
break;
}
BigDecimal rate = new BigDecimal((int)obj.get("total")).divide(new BigDecimal(sum));
rateMap.put((String)obj.get("_id"), rate);
other = other.add(rate);
i ++;
} Instant end = Instant.now();
System.out.println(Duration.between(start, end).toMillis());
} /**
* 一共下了多少单
*/
@Test
public void test06() {
Aggregation aggregation = Aggregation.newAggregation(
match(Criteria.where("userId").is(8744L)),
group("userId").count().as("count"));
AggregationResults<BasicDBObject> result =
mongoTemplate.aggregate(aggregation, MOrder.class, BasicDBObject.class); int count = (int) result.getMappedResults().get(0).get("count");
System.out.println(count);
} /**
* 最喜欢的店铺(即下单最多的店铺)
*/
@Test
public void test07() {
Aggregation aggregation = Aggregation.newAggregation(
match(Criteria.where("userId").is(8744L)),
group("shopId").count().as("count"),
sort(Sort.Direction.DESC, "count"),
limit(1));
AggregationResults<BasicDBObject> result =
mongoTemplate.aggregate(aggregation, MOrder.class, BasicDBObject.class); long shopId = (long) result.getMappedResults().get(0).get("_id");
int count = (int) result.getMappedResults().get(0).get("count");
System.out.println(shopId);
System.out.println(count);
} /**
* 下单最多的那天和下单数量
*/
@Test
public void test08() {
Aggregation aggregation = Aggregation.newAggregation(
match(Criteria.where("userId").is(8744L)),
project().andExpression("{$dateToString:{format:'%Y-%m-%d',date: '$createTime'}}").as("createTime"),
group("createTime").count().as("count"),
sort(Sort.Direction.DESC, "count"),
limit(1));
AggregationResults<BasicDBObject> result =
mongoTemplate.aggregate(aggregation, MOrder.class, BasicDBObject.class);
String day = (String) result.getMappedResults().get(0).get("_id");
int count = (int) result.getMappedResults().get(0).get("count");
System.out.println(day);
System.out.println(count);
} /**
* 花费金额最多的那天和金额
*/
@Test
public void test09() {
Aggregation aggregation = Aggregation.newAggregation(
match(Criteria.where("userId").is(8744L)
.and("createTime").gte(DateUtils.fromString("2018-01-01 16:00:57", "yyyy-MM-dd HH:mm:ss")).lte(new Date())),
project("payAmount").andExpression("{$dateToString:{format:'%Y-%m-%d',date: '$createTime'}}").as("createTime"),
group("createTime").sum("payAmount").as("total"),
sort(Sort.Direction.DESC, "total"),
limit(1));
AggregationResults<BasicDBObject> result =
mongoTemplate.aggregate(aggregation, MOrder.class, BasicDBObject.class);
String day = (String) result.getMappedResults().get(0).get("_id");
BigDecimal amount = ((Decimal128)result.getMappedResults().get(0).get("total")).bigDecimalValue();
System.out.println(day);
System.out.println(amount);
} /**
* 前3笔最多消费
*/
@Test
public void test10() {
Aggregation aggregation = Aggregation.newAggregation(
match(Criteria.where("userId").is(8744L)),
sort(Sort.Direction.DESC, "payAmount"),
limit(3));
AggregationResults<BasicDBObject> result = mongoTemplate.aggregate(aggregation, MOrder.class, BasicDBObject.class); List<MOrder> orders = new ArrayList<>(3); for (BasicDBObject bd : result.getMappedResults()) {
MOrder order = new MOrder();
order.setOrderId(bd.getString("orderId"));
order.setPayAmount((Decimal128) bd.get("payAmount"));
order.setShopId(bd.getLong("shopId"));
order.setCreateTime(bd.getDate("createTime"));
orders.add(order);
}
System.out.println(orders);
} /**
* 第一笔交易信息
*/
@Test
public void test11() {
Aggregation aggregation = Aggregation.newAggregation(
match(Criteria.where("userId").is(8744L)),
sort(Sort.Direction.ASC, "createTime"),
limit(1));
AggregationResults<BasicDBObject> result = mongoTemplate.aggregate(aggregation, MOrder.class, BasicDBObject.class);
BasicDBObject bd = result.getMappedResults().get(0);
MOrder order = new MOrder();
order.setOrderId(bd.getString("orderId"));
order.setPayAmount((Decimal128) bd.get("payAmount"));
order.setShopId(bd.getLong("shopId"));
order.setCreateTime(bd.getDate("createTime"));
System.out.println("第一笔交易时间为 " + DateUtils.formatToString(order.getCreateTime(), "yyyy-MM-dd HH:mm:ss"));
System.out.println("第一笔交易金额为 " + order.getPayAmount().bigDecimalValue().setScale(2, BigDecimal.ROUND_HALF_DOWN));
System.out.println("第一笔交易商家id为 " + order.getShopId());
System.out.println("第一笔交易订单号为 " + order.getOrderId());
} /**
* 查询成为会员的时间和第几位会员
*/
@Test
public void test12() {
Long userId = 1L; Aggregation agg = Aggregation.newAggregation(
match(
Criteria.where("userId").is(userId)
.and("afterUserType").is("FORMAL_VIP")),
sort(Sort.Direction.ASC, "startTime"),
limit(1));
AggregationResults<BasicDBObject> result1 = mongoTemplate.aggregate(agg, MVipRecord.class, BasicDBObject.class); agg = Aggregation.newAggregation(
match(
Criteria.where("startTime")
.lt(result1.getMappedResults().get(0).getDate("startTime"))));
AggregationResults<BasicDBObject> result2 = mongoTemplate.aggregate(agg, MVipRecord.class, BasicDBObject.class);
int count = result2.getMappedResults().size() + 1;
System.out.println("您成为会员的时间:" + DateUtils.formatToString(result1.getMappedResults().get(0).getDate("startTime"), "yyyy-MM-dd hh:mm:ss"));
System.out.println("您是第" + count + "位会员");
} /**
* 查询注册时间和是第几位用户
*/
@Test
public void test13() {
Instant start = Instant.now();
Long userId = 1L;
Aggregation agg = Aggregation.newAggregation(
match(Criteria.where("userId").is(userId)));
AggregationResults<BasicDBObject> result1 = mongoTemplate.aggregate(agg, MUser.class, BasicDBObject.class);
agg = Aggregation.newAggregation(
match(
Criteria.where("createTime")
.lt(result1.getMappedResults().get(0).getDate("createTime"))),
project("userId"));
AggregationResults<BasicDBObject> result2 = mongoTemplate.aggregate(agg, MUser.class, BasicDBObject.class);
int count = result2.getMappedResults().size() + 1;
System.out.println("您成为用户的时间:" + DateUtils.formatToString(result1.getMappedResults().get(0).getDate("createTime"), "yyyy-MM-dd hh:mm:ss"));
System.out.println("您是第" + count + "位注册用户");
Instant end = Instant.now();
System.out.println(Duration.between(start, end).toMillis());
} }
mongoTemplate聚合操作Demo的更多相关文章
- MongoTemplate聚合操作
Aggregation简单来说,就是提供数据统计.分析.分类的方法,这与mapreduce有异曲同工之处,只不过mongodb做了更多的封装与优化,让数据操作更加便捷和易用.Aggregation操作 ...
- 基于 MongoDB 动态字段设计的探索 (二) 聚合操作
业务需求及设计见前文:基于 MongoDB 动态字段设计的探索 根据专业计算各科平均分 (总分.最高分.最低分) public Object avg(String major){ Aggregatio ...
- Java8之Stream 集合聚合操作集锦(含日常练习Demo)
Stream 是用函数式编程方式在集合类上进行复杂操作的工具,其集成了Java 8中的众多新特性之一的聚合操作,开发者可以更容易地使用Lambda表达式,并且更方便地实现对集合的查找.遍历.过滤以及常 ...
- 基于Morphia实现MongoDB按小时、按天聚合操作
MongoDB按照天数或小时聚合 需求 最近接到需求,需要对用户账户下的设备状态,分别按照天以及小时进行聚合,以此为基础绘制设备状态趋势图. 实现思路是启动定时任务,对各用户的设备状态数据分别按照小时 ...
- MongoTemplate聚合(一)$lookup
mongodb 最近入职了新的公司,新公司统一使用的mongodb,es等非关系型数据库.以前对es有一些了解,其实就是灵活的文档类型结构,不受限于关系型数据库的那种字段唯一确定的"死板 ...
- 《Entity Framework 6 Recipes》中文翻译系列 (27) ------ 第五章 加载实体和导航属性之关联实体过滤、排序、执行聚合操作
翻译的初衷以及为什么选择<Entity Framework 6 Recipes>来学习,请看本系列开篇 5-9 关联实体过滤和排序 问题 你有一实体的实例,你想加载应用了过滤和排序的相关 ...
- MongoDB 聚合操作
在MongoDB中,有两种方式计算聚合:Pipeline 和 MapReduce.Pipeline查询速度快于MapReduce,但是MapReduce的强大之处在于能够在多台Server上并行执行复 ...
- .NET LINQ 聚合操作
聚合操作 聚合运算从值集合计算单个值. 从一个月的日温度值计算日平均温度就是聚合运算的一个示例. 方法 方法名 说明 C# 查询表达式语法 Visual Basic 查询表达式语法 更多信息 ...
- Linq查询操作之聚合操作(count,max,min,sum,average,aggregate,longcount)
在Linq中有一些这样的操作,根据集合计算某一单一值,比如集合的最大值,最小值,平均值等等.Linq中包含7种操作,这7种操作被称作聚合操作. 1.Count操作,计算序列中元素的个数,或者计算满足一 ...
随机推荐
- hibernate课程 初探单表映射1-6 hibernate项目建立以及导入jar包
hibernate 项目建立 1 new ==>java project hibernate 导入jar包 1 windows==>prerence==>java ==>bui ...
- JS实现2048
2048这个游戏是通过对二维数组的操作来实现的,其算法核心如下: (以一行左移为例) c从0开始,遍历当前行中的元素,到<CN-1(CN是一个常量,表示的是游戏格子的列数)结束,每次+1 找到当 ...
- 一张图掌握移动Web前端所有技术(大前端、工程化、预编译、自动化)
你要的移动web前端都在这里! 大前端方向:移动Web前端.Native客户端.Node.js. 大前端框架:React.Vue.js.Koa 跨终端技术:HTML 5.CSS 3.JavaScri ...
- cron 任务执行表达式
1.来源 开始我还不知道cron到底来源于哪里,不求甚解的我也没做过多了解,现在突然用到所以写一下. cron计划任务 其实只是linux 一个执行计划的一个工具或者执行程序. 在Linux系统中, ...
- Centos_linux系统的区别及实际查看
在Linux系统查看系统版本为 32 位还是 64 位 [root@localhost ~]# cat /etc/redhat-release CentOS release 6.8 (Final) [ ...
- java 千分位的添加和去除
转至:http://blog.sina.com.cn/s/blog_8f99a1640102v1xh.html 将一个数字转换为有千分位的格式: NumberFormat numberFormat1 ...
- 【来龙去脉系列】QRCode二维码的生成细节和原理
二维码又称QR Code,QR全称Quick Response,是一个近几年来移动设备上超流行的一种编码方式,它比传统的Bar Code条形码能存更多的信息,也能表示更多的数据类型:比如:字符,数字, ...
- Intel&amd
- Redis多机数据库
复制 PSYNC命令具有完整重同步(full resynchronization)和部分重同步(partial resynchronization)两种模式: ·其中完整重同步用于处理初次复制情况:完 ...
- IOS 拖拽事件(手势识别)
@interface NJViewController () @property (weak, nonatomic) IBOutlet UIView *customView; @end @implem ...