执行 MongoTemplate.aggregate 而不检索行

Execute MongoTemplate.aggregate without row retrival

我正在使用 Spring Mongo 驱动程序执行一个大型 mongo 聚合语句,该语句将 运行 持续一段时间。此聚合的输出阶段将聚合的输出写入新集合。在任何时候我都不需要在内存中检索此聚合的结果。

当我 运行 在 Spring 启动时,JVM 在进行行检索时 运行 内存不足,尽管我没有使用或存储任何结果。

有没有办法使用 MongoTemplate.aggregate 跳过行检索?

例如:

mongoTemplate.aggregate(Aggregation.newAggregation(
   Aggregation.sort(new Sort(new Sort.Order(Sort.Direction.DESC, "createdOn"))),

   Aggregation.group("accountId")
      .first("bal").as("bal")
      .first("timestamp").as("effectiveTimestamp"),

   Aggregation.project("_id", "effectiveTimestamp")
                        .andExpression("trunc(bal * 10000 + 0.5) / 100").as("bal"),

   aggregationOperationContext -> new Document("$addFields", new Document("history",Arrays.asList(historyObj))),

   // Write results out to a new collection - Do not store in memory
   Aggregation.out("newBalance")
).withOptions(Aggregation.newAggregationOptions().allowDiskUse(true).build()),
   "account", Object.class
);

我使用

解决了这个问题
MongoTempalte.aggregateStream(...).withOptions(Aggregation.newAggregationOptions().cursorBatchSize(0).build)

使用聚合选项 - skipOutput()。如果聚合管道包含 $out/$merge 操作,这不会 return 结果。

mongoTemplate.aggregate(aggregation.withOptions(newAggregationOptions().skipOutput().allowDiskUse(true).build()), "collectionNme", EntityClass.class);

如果您使用的是没有框架的 MongoDriver。

MongoClient client = MongoClients.create("mongodb://localhost:27017");
 MongoDatabase database = client.getDatabase("my-collection");
 MongoCollection<Document> model = database.getCollection(collectionName);
 AggregateIterable<Document> aggregateResult = model.aggregate(bsonListOfAggregationPipeline);
 
 // instead iterating over call toCollection() to skipResult
 aggregateIterable.toCollection();

参考文献: