die*_*ter 4 java mongodb spring-data spring-data-mongodb
我可以通过使用这个mongodb本机查询来做到这一点:
db.books.aggregate(
[ { $sample: { size: 15 } } ]
)
Run Code Online (Sandbox Code Playgroud)
但是怎么做呢spring-data-mongodb?
我在Spring Aggregation Framework的Aggregation类中找不到类似的操作
更新:
从Spring Data v2.0开始,您可以这样做:
SampleOperation matchStage = Aggregation.sample(5);
Aggregation aggregation = Aggregation.newAggregation(sampleStage);
AggregationResults<OutType> output = mongoTemplate.aggregate(aggregation, "collectionName", OutType.class);
Run Code Online (Sandbox Code Playgroud)
原始答案:
像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);
}
}
Run Code Online (Sandbox Code Playgroud)
然后在你的代码中使用:
Aggregation aggregation = newAggregation(
new CutomAggregationOperation(
new BasicDBObject(
"$sample",
new BasicDBObject( "size", 15 )
)
)
);
Run Code Online (Sandbox Code Playgroud)
由于这实现了AggregationOperation这适用于exising管道操作辅助方法.即:
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")))
)
);
Run Code Online (Sandbox Code Playgroud)
所以,在一天结束时,一切都只是一个BSON对象.这只是一个接口包装器的问题,以便spring-mongo中的类方法解释结果并正确获取您定义的BSON对象.
| 归档时间: |
|
| 查看次数: |
1746 次 |
| 最近记录: |