java操作mongodb(聚合函数)

数据库数据如下:

 

上代码:

public static void main(String[] args) {
		 UserDao userDao = new UserDao();
		 userDao.juhe();
	}

	public void juhe() {
		DB myMongo = MongoManager.getDB("myMongo");
		DBCollection userCollection = myMongo.getCollection("user");

		// 使用 count 统计数量
		System.out.println(userCollection.count());

		// 使用distinct 统计所有的address
		List distinct = userCollection.distinct("address");
		System.out.println(distinct);

		//使用group 查询每年(year)中age最大的人
		BasicDBObject key = new BasicDBObject("year",true);   
		BasicDBObject cond = new BasicDBObject("id",new BasicDBObject(QueryOperators.GT,0));   
		BasicDBObject initial = new BasicDBObject("age",0);   
		String reduce = "function (doc,prev){"
							+"if(doc.age>prev.age){"
								+"prev.age=doc.age;"
								+"prev.name=doc.name"
							+"}"
						+"}";
		BasicDBList group =  (BasicDBList) userCollection.group(key,cond,initial,reduce);    
		System.out.println(group); 

	}


 

输出结果如下:

11
[ "1" , "2" , "5" , "6" , "7" , "8" , "9" , "11" , "12"]
[ { "year" : 2014.0 , "age" : 17.0 , "name" : "2"} , { "year" : 2013.0 , "age" : 17.0 , "name" : "2"}]


 

### 如何在 Java 中使用 MongoDB 聚合函数 #### 使用 `MongoTemplate` 进行聚合操作 Spring Data MongoDB 提供了一个强大的工具类 `MongoTemplate`,它允许开发者通过构建管道阶段来执行复杂的聚合查询。以下是基于 Spring 的实现方式: ```java import org.springframework.beans.factory.annotation.Autowired; 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.aggregation.MatchOperation; import org.springframework.data.mongodb.core.aggregation.SortOperation; import org.springframework.data.mongodb.core.aggregation.UnwindOperation; import org.springframework.stereotype.Service; @Service public class MongoAggregationService { @Autowired private MongoTemplate mongoTemplate; public List<Document> getSortedTweetList(String objectId) { MatchOperation matchStage = Aggregation.match( Criteria.where("_id").is(new ObjectId(objectId)) ); UnwindOperation unwindStage = Aggregation.unwind("tweet_list"); MatchOperation tweetMatchStage = Aggregation.match( Criteria.where("tweet_list.timestamp_ms").is("1451841845660") ); SortOperation sortStage = Aggregation.sort(Sort.Direction.ASC, "tweet_list.timestamp_ms"); Aggregation aggregation = Aggregation.newAggregation(matchStage, unwindStage, tweetMatchStage, sortStage); AggregationResults<Document> results = mongoTemplate.aggregate(aggregation, "text", Document.class); return results.getMappedResults(); } } ``` 上述代码展示了如何利用 `MongoTemplate` 构建一个多阶段的聚合管道[^4]。 --- #### 原生驱动器中的聚合操作 如果未使用 Spring 数据库框架,则可以依赖于 MongoDB 官方提供的原生 Java 驱动程序完成相同的任务。以下是一个不借助任何额外框架的示例: ```java import com.mongodb.client.*; import org.bson.Document; import java.util.ArrayList; import java.util.Arrays; import java.util.List; public class NativeMongoAggregation { public static void main(String[] args) { MongoClient client = MongoClients.create("mongodb://localhost:27017"); MongoDatabase database = client.getDatabase("testDb"); MongoCollection<Document> collection = database.getCollection("text"); List<Bson> pipeline = Arrays.asList( new Document("$match", new Document("_id", new ObjectId("5ca95b4bfb60ec43b5dd0db5"))), new Document("$unwind", "$tweet_list"), new Document("$match", new Document("tweet_list.timestamp_ms", "1451841845660")), new Document("$sort", new Document("tweet_list.timestamp_ms", 1)) ); AggregateIterable<Document> result = collection.aggregate(pipeline); for (Document doc : result) { System.out.println(doc.toJson()); } client.close(); } } ``` 此方法直接调用了 MongoDB 的原生 API 来定义和运行聚合管道[^2]。 --- #### 关键概念解析 - **$match**: 筛选出符合条件的文档集合。 - **$unwind**: 将数组字段拆分为多个独立的文档记录。 - **$sort**: 对结果集按照指定字段升序或降序排列。 这些操作符必须嵌套在 `$pipeline` 表达式内部才能生效[^3]。 --- ### 总结 无论是采用 Spring Data MongoDB 提供的高级抽象接口还是直接运用 MongoDB 原生驱动器,都可以灵活地实现复杂的数据聚合需求。推荐优先考虑前者以便简化开发流程并提高可维护性。
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值