springboot-mongodb Aggregation操作(下)

https://blog.csdn.net/congcong68/article/details/52821362


在Spring Boot中整合MongoDB,可以使用MongoTemplate来执MongoDB操作。而$unionWith是MongoDB 4.4版本中新增的集合操作符,可以用于将两个集合合并成一个集合。 在MongoTemplate中使用$unionWith操作符,可以通过以下步骤实现: 1. 定义两个集合的AggregationOperation对象: ``` AggregationOperation firstCollection = Aggregation.match(Criteria.where("field1").is("value1")); AggregationOperation secondCollection = Aggregation.match(Criteria.where("field2").is("value2")); ``` 2. 创建$unionWith操作符的AggregationOperation对象: ``` AggregationOperation unionWith = Aggregation.unionWith("second_collection", firstCollection, secondCollection); ``` 其中,"second_collection"表示要将结果合并到哪个集合中。 3. 执聚合操作: ``` AggregationResults<Document> results = mongoTemplate.aggregate(unionWith, "first_collection", Document.class); List<Document> documents = results.getMappedResults(); ``` 其中,"first_collection"表示要执聚合操作的集合。 完整示例代码如下: ``` AggregationOperation firstCollection = Aggregation.match(Criteria.where("field1").is("value1")); AggregationOperation secondCollection = Aggregation.match(Criteria.where("field2").is("value2")); AggregationOperation unionWith = Aggregation.unionWith("second_collection", firstCollection, secondCollection); AggregationResults<Document> results = mongoTemplate.aggregate(unionWith, "first_collection", Document.class); List<Document> documents = results.getMappedResults(); ``` 注意,使用$unionWith操作符需要MongoDB 4.4及以上版本支持。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值