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操作,计算序列中元素的个数,或者计算满足一 ...
随机推荐
- 给 Magento 2 添加缓存层的分析与尝试
虽然黑色星期五有惊无险的过去了, 但是 Magento 2 社区版无法读写分离这个限制, 始终是悬在整个网站上的一把利剑. 我之前尝试过给 Magento 2 写一个 MySQL 读写分离的插件, 在 ...
- 洛谷P1397 [NOI2013]矩阵游戏(十进制矩阵快速幂)
题意 题目链接 Sol 感觉做这题只要对矩阵乘法理解的稍微一点就能做出来对于每一行构造一个矩阵A = a 1 0 b列与列之间的矩阵为B = c 1 0 d最终答案为$A^{n - ...
- js和jq获取父,兄弟,子节点
1,js获取节点: 父: parentNode 获取已知节点的父节点. 子: childNodes; 得到全部子节点 children 得到全部子节点 firstChild 获得第一个子节点 last ...
- SpringBoot的核心功能
1.独立运行的Spring项目 SpringBoot可以以jar包的形式独立运行,运行一个SpringBoot项目只需要通过java -jar xx.jar来启动. 2.内嵌Servlet容器 Spr ...
- python:使用OpenSSL
(一)安装pyOpenSSL 1.下载并安装 https://launchpad.net/pyopenssl pyOpenSSL-0.11.winxp32-py2.7.msi ...
- IOS Quartz2D自定义view
@property (nonatomic, weak) UIImageView *imageView; @property (nonatomic, weak) NJImageView *njIv; @ ...
- top命令交互快捷键
#toptop - :: up :, users, load average: 0.17, 0.12, 0.14 Tasks: total, running, sleeping, stopped, z ...
- NOIP2018提高组Day2 解题报告
前言 关于\(NOIP2018\),详见此博客:NOIP2018学军中学游记(11.09~11.11). \(Day2\)的题目和\(Day1\)比起来,真的是难了很多啊. \(T1\):旅行(点此看 ...
- 【洛谷3950】部落冲突(LCT维护连通性)
点此看题面 大致题意: 给你一棵树,\(3\)种操作:连一条边,删一条边,询问两点是否联通. \(LCT\)维护连通性 有一道类似的题目:[BZOJ2049][SDOI2008] Cave 洞穴勘测. ...
- Java统计用户年/月/周/日网站访问量
一:准备工作,引入相关依赖: 二:运行效果图: 下一次访问 三:具体代码如下 (1):CountObjectInfo.java package cn.csrc.base.count; import ...