使用spring-data-mongodb传输聚合操作的结果

我正在使用spring-data-mongodb,并且想使用游标进行聚合操作。

MongoTemplate.stream() 得到一个查询,所以我试图创建聚合实例,将其转换为 DBOBJECT 使用

Aggregation.toDbObject() ,创建了一个 BasicQuery 使用 DBOBJECT ,然后调用 流() 方法。

这将返回一个空游标。

调试spring-data-mongodb代码显示 MongoTemplate.stream() 使用 FindOperation

,这使我认为thinkspring-data-mongodb不支持流式聚合操作。

有谁能够使用spring-data-mongodb来流式传输聚合查询的结果?

作为记录,我可以使用Java mongodb驱动程序来实现,但是我更喜欢使用spring-data。

11月10日-添加示例代码:

    MatchOperation match = Aggregation.match(Criteria.where("type").ne("AType"));

GroupOperation group = Aggregation.group("name", "type");

group = group.push("color").as("colors");

group = group.push("size").as("sizes");

TypedAggregation<MyClass> agg = Aggregation.newAggregation(MyClass.class, Arrays.asList(match, group));

MongoConverter converter = mongoTemplate.getConverter();

MappingContext<? extends MongoPersistentEntity<?>, MongoPersistentProperty> mappingContext = converter.getMappingContext();

QueryMapper queryMapper = new QueryMapper(converter);

AggregationOperationContext context = new TypeBasedAggregationOperationContext(MyClass.class, mappingContext, queryMapper);

// create a BasicQuery to be used in the stream() method by converting the Aggregation to a DbObject

BasicQuery query = new BasicQuery(agg.toDbObject("myClass", context));

// spring-mongo attributes the stream() method to find() operationsm not to aggregate() operations so the stream returns an empty cursor

CloseableIterator<MyClass> iter = mongoTemplate.stream(query, MyClass.class);

// this is an empty cursor

while(iter.hasNext()) {

System.out.println(iter.next().getName());

}

以下代码未使用stream()方法,返回了预期的聚合非空结果:

    AggregationResults<HashMap> result = mongoTemplate.aggregate(agg, "myClass", HashMap.class);

回答:

对于那些仍在寻找答案的人:

从spring-data-mongo版本2.0.0.M4开始(

MongoTemplate得到了一种aggregateStream方法。

因此,您可以执行以下操作:

 AggregationOptions aggregationOptions = Aggregation.newAggregationOptions()

// this is very important: if you do not set the batch size, you'll get all the objects at once and you might run out of memory if the returning data set is too large

.cursorBatchSize(mongoCursorBatchSize)

.build();

data = mongoTemplate.aggregateStream(Aggregation.newAggregation(

Aggregation.group("person_id").count().as("count")).withOptions(aggregationOptions), collectionName, YourClazz.class);

以上是 使用spring-data-mongodb传输聚合操作的结果 的全部内容, 来源链接: utcz.com/qa/415398.html

回到顶部