提示:文章写完后,目录可以自动生成,如何生成可参考右边的帮助文档
db.electric.aggregate([{
$match: {
_id: {
$eq: '123456'
}
}
},
{
$project: {
content: {
$filter: {
input: '$content',
as: 'item',
cond: {
$lte: ['$$item.t', 1641657612000]
}
}
}
}
}
])
这只是一个示例,除了$filter,其余网上皆有大佬们的文档给出用法
代码如下(示例):
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 聚合查询 子文档过滤》文章.
源码很重要,英文也很重要,系统的学习探讨更重要,望大家记得