MongoDB Aggregate官方案例的Java实现

操作参考文档

更多的聚合操作与计算操作文档地址:
中文文档:https://docs.mongoing.com/can-kao/yun-suan-fu/aggregation-pipeline-operators
英文文档:https://www.mongodb.com/docs/manual/reference/operator/aggregation

官方案例

https://www.mongodb.com/docs/manual/core/aggregation-pipeline/

案例一

1. 数据

db.orders.insertMany( [
   { _id: 0, name: "Pepperoni", size: "small", price: 19,
	 quantity: 10, date: ISODate( "2021-03-13T08:14:30Z" ) },
   { _id: 1, name: "Pepperoni", size: "medium", price: 20,
	 quantity: 20, date : ISODate( "2021-03-13T09:13:24Z" ) },
   { _id: 2, name: "Pepperoni", size: "large", price: 21,
	 quantity: 30, date : ISODate( "2021-03-17T09:22:12Z" ) },
   { _id: 3, name: "Cheese", size: "small", price: 12,
	 quantity: 15, date : ISODate( "2021-03-13T11:21:39.736Z" ) },
   { _id: 4, name: "Cheese", size: "medium", price: 13,
	 quantity:50, date : ISODate( "2022-01-12T21:23:13.331Z" ) },
   { _id: 5, name: "Cheese", size: "large", price: 14,
	 quantity: 10, date : ISODate( "2022-01-12T05:08:13Z" ) },
   { _id: 6, name: "Vegan", size: "small", price: 17,
	 quantity: 10, date : ISODate( "2021-01-13T05:08:13Z" ) },
   { _id: 7, name: "Vegan", size: "medium", price: 18,
	 quantity: 10, date : ISODate( "2021-01-13T05:10:13Z" ) }
] )

2. 参照MySQL

select name as id,sum(quantity)
from orders
where size = 'medium'
group by name

3. 聚合语句

db.orders.aggregate( [
   // Stage 1: Filter pizza order documents by pizza size
   {
	  $match: { size: "medium" }
   },
   // Stage 2: Group remaining documents by pizza name and calculate total quantity
   {
	  $group: { _id: "$name", totalQuantity: { $sum: "$quantity" } }
   }
] )

4. Java代码实现

@Test
public void aggregation1(){
	Aggregation aggregation = Aggregation.newAggregation(
			Aggregation.match(new Criteria().and("size").is("medium")),
			Aggregation.group("id").first("id").as("id")
			.sum("quantity").as("totalQuantity")
	);
	AggregationResults<OrdersEntity> aggregate = mongoTemplate.aggregate(aggregation, Orders.class, OrdersEntity.class);
	for (OrdersEntity ordersEntity : aggregate) {
		System.out.println(ordersEntity);
	}
}

案例二

1. 参照SQL

SELECT 
	a.id,
	a.totalOrderValue,
	a.averageOrderQuantity
FROM (
	SELECT
		DATE_FORMAT( date, '%Y-%m-%d' ) AS id,
		sum( price * quantity ) as totalOrderValue,
		avg( quantity ) as averageOrderQuantity
	FROM
		orders 
	WHERE 1=1
		AND date >= "2020-01-30" 
		AND date <= "2022-01-30" 
	GROUP BY
	DATE_FORMAT( date, '%Y-%m-%d' )
) a
ORDER BY a.totalOrderValue

2. 聚合语句

db.orders.aggregate( [

   // Stage 1: Filter pizza order documents by date range
   {
	  $match:
	  {
		 "date": { $gte: new ISODate( "2020-01-30" ), $lt: new ISODate( "2022-01-30" ) }
	  }
   },

   // Stage 2: Group remaining documents by date and calculate results
   {
	  $group:
	  {
		 _id: { $dateToString: { format: "%Y-%m-%d", date: "$date" } },
		 totalOrderValue: { $sum: { $multiply: [ "$price", "$quantity" ] } },
		 averageOrderQuantity: { $avg: "$quantity" }
	  }
   },


   // Stage 3: Sort documents by totalOrderValue in descending order
   {
	  $sort: { totalOrderValue: -1 }
   }

 ] )

3. Java代码实现

@Test
public void aggregation2(){
	Calendar from = Calendar.getInstance();
	from.set(2020,Calendar.JANUARY,30);
	Calendar to = Calendar.getInstance();
	to.set(2022,Calendar.JANUARY,30);
	Criteria criteria = new Criteria();
	criteria.andOperator(Criteria.where("date").gte(from.getTime()).lte(to.getTime()));
	Aggregation aggregation = Aggregation.newAggregation(
			Aggregation.match(criteria),
			Aggregation.project("date","quantity")
					.andExpression("{$dateToString:{format:'%Y-%m-%d',date:'$date'}}").as("id")
					.andExpression("{$multiply:{'$price','$quantity'}}").as("priceMultiQuantity"),
			Aggregation.group("id")
					.sum("priceMultiQuantity").as("totalOrderValue")
					.avg("quantity").as("averageOrderQuantity"),
			Aggregation.sort(Sort.by(Sort.Direction.DESC,"totalOrderValue"))
	);
	AggregationResults<OrdersEntity> aggregate = mongoTemplate.aggregate(aggregation, Orders.class, OrdersEntity.class);
	for (OrdersEntity ordersEntity : aggregate) {
		System.out.println(ordersEntity);
	}
}
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
你可以使用MongoDB的聚合框架来进行去重统计。下面是一个Java实现的例子: ```java import com.mongodb.MongoClient; import com.mongodb.client.AggregateIterable; import com.mongodb.client.MongoCollection; import com.mongodb.client.MongoDatabase; import static com.mongodb.client.model.Accumulators.*; import static com.mongodb.client.model.Aggregates.*; import static com.mongodb.client.model.Filters.*; import org.bson.Document; public class DistinctCountExample { public static void main(String[] args) { // 连接MongoDB MongoClient mongoClient = new MongoClient("localhost", 27017); // 获取数据库 MongoDatabase database = mongoClient.getDatabase("mydb"); // 获取集合 MongoCollection<Document> collection = database.getCollection("mycollection"); // 聚合查询 AggregateIterable<Document> iterable = collection.aggregate( Arrays.asList( // 分组统计去重后的数量 group("$field1", sum("count", 1)), // 投影出结果 project(fields(excludeId(), include("field1", "count"))) ) ); // 输出结果 for (Document document : iterable) { System.out.println(document.toJson()); } // 关闭连接 mongoClient.close(); } } ``` 这个例子中,我们使用了MongoDB的聚合框架来进行去重统计。首先,我们使用`group`操作符对`field1`字段进行分组,并使用`sum`操作符来统计每个分组中元素的数量。然后,我们使用`project`操作符来投影出结果集,包含`field1`字段和去重后的`count`字段,即每个元素在`field1`字段中出现的次数。最终得到去重后的统计结果。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

加把劲骑士RideOn

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值