更新:
从 Spring Data v2.0 开始,您可以这样做:
SampleOperation matchStage = Aggregation.sample(5);
Aggregation aggregation = Aggregation.newAggregation(sampleStage);
AggregationResults<OutType> output = mongoTemplate.aggregate(aggregation, "collectionName", OutType.class);
原答案:
像 spring-mongo 这样的抽象层总是会落后于服务器发布的功能。因此,您最好自己为流水线阶段构建 BSON 文档结构。
在自定义类中实现:
public class CustomAggregationOperation implements AggregationOperation {
private DBObject operation;
public CustomAggregationOperation (DBObject operation) {
this.operation = operation;
}
@Override
public DBObject toDBObject(AggregationOperationContext context) {
return context.getMappedObject(operation);
}
}
然后在你的代码中使用:
Aggregation aggregation = newAggregation(
new CutomAggregationOperation(
new BasicDBObject(
"$sample",
new BasicDBObject( "size", 15 )
)
)
);
由于它实现了AggregationOperation,因此它可以很好地与现有的管道操作辅助方法一起使用。即:
Aggregation aggregation = newAggregation(
// custom pipeline stage
new CutomAggregationOperation(
new BasicDBObject(
"$sample",
new BasicDBObject( "size", 15 )
)
),
// Standard match pipeline stage
match(
Criteria.where("myDate")
.gte(new Date(new Long("949384052490")))
.lte(new Date(new Long("1448257684431")))
)
);
再说一遍,归根结底,一切都只是一个 BSON 对象。这只是一个接口包装器的问题,以便 spring-mongo 中的类方法解释结果并正确获取您定义的 BSON 对象。