spring mongo填坑-聚合查询时查询条件要放在前面

Spring的MongoTemplate提供了聚合查询的接口,我写了一个简单聚合查询
List<AggregationOperation> operations = new ArrayList();
operations.add(Aggregation.group(new String[]{"field1,filed2"}).count().as("count"));
operations.add(Aggregation.sort(Sort.Direction.DESC, "field1"));
operations.add(Aggregation.skip(skip));
operations.add(Aggregation.limit(limit));
operations.add(Aggregation.match(Criteria.where("field1").in(fields)));
Aggregation aggregation = Aggregation.newAggregation(operations);BicDBObject.class);
AggregationResults<BasicDBObject> results = mongoDdlpdbTemplate.aggregate(aggregation, Bean.class, BasicDBObject.class);

结果查出来结果是空.

刚开始考虑是不是查询条件出问题了,于是原样查询改成Query

Query query = new Query();
query.with(new Sort(Sort.Direction.DESC, "field1"));
query.skip(skip);
query.limit(limit);
query.addCriteria(Criteria.where("field1").in(fields));
List<Bean> list = mongoDdlpdbTemplate.find(query,Bean.class);

查询结果没问题

于是猜测是不是group影响了查询

去掉group查询

List<AggregationOperation> operations = new ArrayList();
operations.add(Aggregation.sort(Sort.Direction.DESC, "field1"));
operations.add(Aggregation.skip(skip));
operations.add(Aggregation.limit(limit));
operations.add(Aggregation.match(Criteria.where("field1").in(fields)));
Aggregation aggregation = Aggregation.newAggregation(operations);
AggregationResults<BasicDBObject> results = mongoDdlpdbTemplate.aggregate(aggregation, Bean.class, BasicDBObject.class);

结果没问题,这样明显是查询语句放的地方不对了,于是调整查询语句顺序,放在group前

List<AggregationOperation> operations = new ArrayList();
operations.add(Aggregation.match(Criteria.where("field1").in(fields)));
operations.add(Aggregation.group(new String[]{"field1,filed2"}).count().as("count"));
operations.add(Aggregation.sort(Sort.Direction.DESC, "field1"));
operations.add(Aggregation.skip(skip));
operations.add(Aggregation.limit(limit));
Aggregation aggregation = Aggregation.newAggregation(operations);BicDBObject.class);
AggregationResults<BasicDBObject> results = mongoDdlpdbTemplate.aggregate(aggregation, Bean.class, BasicDBObject.class);   

查询结果正常

但是我去查了下资料,mongo语法里面是没有说查询语句要在聚合语句之前的,具体原因有待探究

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值