MongoTemplate分组排序取第一条记录

本文介绍如何使用MongoTemplate在MongoDB中通过分组操作,按照文件路径对流文件进行过滤并获取每个路径下的最新版本记录。通过聚合管道实现,包括match、sort和group操作,最后返回处理后的StreamFile对象列表。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

MongoTemplate分组排序取第一条记录

在开发过程中,竟然遇到这样一个需求,按照某一个字段或者某个查询条件进行分组。分组后取其最新的一条数据。
例如:在查询文件版本时,要求根据文件路径filePath分组,表示每一组都是同一个文件,只是版本不同。分组后,每组取出版本号最高(即最新)的一个。

目前在网上找到的可行的代码如下,Aggregates.match目前只支持对某个字段过滤,支持多条件查询暂时不知如何处理。

public List<StreamFile> findRootChildrenByStreamId(String projectId, String streamId, String parentId){
		AggregateIterable<Document> aggregateIterable = dao.getTemplate(projectId).getCollection(dao.getCollectionName(StreamFile.class))
				.aggregate(Arrays.asList(
						// 按照parentId列表过滤记录
						Aggregates.match(Filters.in(StreamFile.FIELD_parentId, streamId)),
						// 按照version降序 排序
						Aggregates.sort(new Document().append(StreamFile.FILED_version,-1)),
						// 根据orderId分组
						Aggregates.group(
								new Document("_id", "$"+StreamFile.FILED_fullPath),
								Arrays.asList(
										// 取分组第一条数据,即version最大的那条,放到doc字段里,供后续的replaceRoot替换用
										Accumulators.first("doc","$$ROOT"))
						),
						// 如果你的API中有Aggregates.replaceRoot,直接使用就可以了
						Aggregates.replaceRoot("$doc")
				));
		List<StreamFile> list = new ArrayList<>();
		for (Document document : aggregateIterable) {
			// 遍历document进行处理
			Object streamID = document.get(StreamFile.FILED_streamId);
			Object parentID = document.get(StreamFile.FIELD_parentId);
			Object fullPath = document.get(StreamFile.FILED_fullPath);
			Object version = document.get(StreamFile.FILED_version);
			StreamFile streamFile = new StreamFile();
			streamFile.setStreamId((String) streamID);
			streamFile.setParentId((String) parentID);
			streamFile.setFullPath((String) fullPath);
			streamFile.setVersion((Integer) version);
			list.add(streamFile);
		}
		return list;
	}

参考:https://blog.youkuaiyun.com/lzufeng/article/details/117378152

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值