mongo对大数据集进行aggregate集合操作,处理各stage阶段中,为了避免 pipeline 的 stage 的内存使用超过 100 MB 而报错。需要设置allowDiskUse为true使用系统缓存,以临时文件进行存储。
Spring Data MongoDB api不同版本对allowDiskUse设置的操作写法不同。
对于Spring Data MongoDB 1.5.x以上2.0版本以下版本并没有提供显式的封装需要自己创建:
AggregationOptions aggregationOptions = new AggregationOptions(true, false, null);
传参true设置allowDiskUse属性。
2.0及以上版本提供内部静态类,以builder的方式设置:
AggregationOptions aggregationOptions = AggregationOptions.builder().allowDiskUse(true).build();
使用示例:
TypedAggregation<Device> countAggr = Aggregation.newAggregation(Device.class,
Aggregation.match(criteria), Aggregation.group().count().as("count")).withOptions(aggregationOptions);
AggregationResults<Document> aggregate = mongoTemplate.aggregate(countAggr, Document.class);
也可以使用原生的写法进行设置,示例:
List<Document> aggregatelist = new ArrayList<>();
//条件1
Document matchdoc = new Document("$match",
new Document("countycode", new Document("$exists", true)));
//条件2
Document groupdoc = new Document("$group",
new Document("_id",
new Document("areacode", "$areacode").append("countycode", "$countycode")
.append("countyname", "$countyname").append("manufacturer",
"$manufacturer")).append("totalcount",
new Document("$sum", 1)));
aggregatelist.add(matchdoc); //{}查询条件
aggregatelist.add(groupdoc); //{}查询条件
MongoConnectionPool.getDatabase(“数据库名”).getCollection("表名")
.aggregate(aggregatelist).allowDiskUse(true).iterator()