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()