gpt4 book ai didi

java - 执行 MongoTemplate.aggregate 而不进行行检索

转载 作者:太空宇宙 更新时间:2023-11-04 09:04:24 24 4
gpt4 key购买 nike

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

当我在 Spring boot 中运行此程序时,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
);

最佳答案

使用 AggregationOption - skipOutput() 。如果聚合管道包含 $out/$merge 操作,这将不会返回结果。

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

引用文献:

关于java - 执行 MongoTemplate.aggregate 而不进行行检索,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60402223/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com