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语法里面是没有说查询语句要在聚合语句之前的,具体原因有待探究