spring-data-mongo Aggregation 聚合查询 子文档过滤

提示:文章写完后,目录可以自动生成,如何生成可参考右边的帮助文档


前言

spring-data-mongo MongoTemplate Aggregation 聚合查询 子文档过滤 我在网上很难找到相关的正确的文章介绍filter的过滤,然后自己摸索加大量的百度搜索,终于找到了正确的用法分享给大家

一、MongoDB的用法

db.electric.aggregate([{
		$match: {
			_id: {
				$eq: '123456'
			}
		}
	},
	{
		$project: {
			content: {
				$filter: {
					input: '$content',
					as: 'item',
					cond: {
						$lte: ['$$item.t', 1641657612000]
					}
				}
			}
		}
	}
])

这只是一个示例,除了$filter,其余网上皆有大佬们的文档给出用法

二、MongoTemplate的说明

下面是我结合大佬们的用法和源码找到的新方法

代码如下(示例):

Aggregation aggregation = Aggregation.newAggregation(
                Aggregation.match(Criteria.where("_id").is("123456")),
                Aggregation.project().and("content").filter("item", AggregationExpression.from(MongoExpression.
                        create("{$and:[{$gte:[\"$$item.t\",1641657602000]},{$lte:[\"$$item.t\", 1641657612000]}]}"))).as("content")
        ).withOptions(AggregationOptions.builder().allowDiskUse(true).build());
System.out.println(aggregation.toString());
return mongoTemplate.aggregate(aggregation, "test", Test.class).getMappedResults();

.filter()方法给出的源码ProjectionOperation是这样的

public ProjectionOperation.ProjectionOperationBuilder filter(String as, AggregationExpression condition) {
            return this.operation.and((AggregationExpression)Filter.filter(this.getRequiredName()).as(as).by(condition));
}

as可以和MongoDB的$filter里的as对应,那condition只能对应$filter里的cond了,然而AggregationExpression是虚拟类并继承MongoExpression,我百度无法找到AggregationExpression的用法,但却找到了相关的MongoExpression的用法,最终用AggregationExpression.from(MongoExpression.create(“XXXX”)的方式代替$filte的cond并打印传入的sql语句,得到:

{
	"aggregate": "__collection__",
	"pipeline": [{
		"$match": {
			"_id": {
				"$eq":  "123456"
			}
		}
	}, {
		"$project": {
			"content": {
				"$filter": {
					"input": "$content",
					"as": "item",
					"cond": {
						"$and": [{
							"$gte": ["$$item.t", 1641657600000]
						}, {
							"$lte": ["$$item.t", 1641659400000]
						}]
					}
				}
			}
		}
	}],
	"allowDiskUse": true
}

此结果是我处理过的,但方法没错!
在此感谢: Haiyoung的《spring-data-mongo Aggregation 聚合查询 子文档过滤》文章.

总结

源码很重要,英文也很重要,系统的学习探讨更重要,望大家记得

  • 2
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Spring Data MongoDB 中,`MongoWriter` 接口用于将对象转换为 MongoDB 文档并插入到集合中。`doInsertBatch` 方法是 `MongoTemplate` 类中的一个方法,用于批量插入数据。 下面是一个简单的示例,展示了如何使用 `MongoWriter` 和 `doInsertBatch` 方法将对象批量插入到 MongoDB 集合中: ```java public class Person { private String name; private int age; // getters and setters } public class PersonWriter implements MongoWriter<Person> { @Override public Document toDocument(Person object, MongoConverter converter) { Document document = new Document(); document.put("name", object.getName()); document.put("age", object.getAge()); return document; } } public class PersonDao { private MongoTemplate mongoTemplate; public void insertBatch(List<Person> persons) { mongoTemplate.execute(Person.class, collection -> { List<Document> documents = new ArrayList<>(); for (Person person : persons) { MongoWriter<Person> writer = new PersonWriter(); Document document = writer.toDocument(person, mongoTemplate.getConverter()); documents.add(document); } collection.insertMany(documents); return null; }); } } ``` 在上面的示例中,`PersonWriter` 类实现了 `MongoWriter` 接口,并重写了 `toDocument` 方法,将 `Person` 对象转换为 MongoDB 文档。`PersonDao` 类中的 `insertBatch` 方法使用 `MongoTemplate` 的 `execute` 方法执行 MongoDB 操作。在该方法内部,首先将传入的 `Person` 对象列表转换为 MongoDB 文档,并将这些文档存储在 `documents` 列表中。最后,使用 `collection.insertMany` 方法将文档批量插入到 MongoDB 集合中。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值