问题描述
我可以通过使用这个 mongodb 本机查询来做到这一点一个>:
I'm able to do it by using this mongodb native query:
db.books.aggregate( [ { $sample: { size: 15 } } ] )
但是如何在 spring-data-mongodb 中做到呢?
But how to do it in spring-data-mongodb ?
聚合类="nofollow">Spring 聚合框架
I found no similar operation in Aggregation class of Spring Aggregation Framework
推荐答案
更新:
从 Spring Data v2.0 开始,您可以这样做:
Starting with v2.0 of Spring Data you can do this:
SampleOperation matchStage = Aggregation.sample(5); Aggregation aggregation = Aggregation.newAggregation(sampleStage); AggregationResults<OutType> output = mongoTemplate.aggregate(aggregation, "collectionName", OutType.class);
<小时>
原答案:
像 spring-mongo 这样的抽象层总是会落后于服务器发布的功能.因此,您最好自己为流水线阶段构建 BSON 文档结构.
Abstraction layers like spring-mongo are always going to lag way behind server released features. So you are best off contructing the BSON document structure for the pipeline stage yourself.
在自定义类中实现:
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); } }
然后在你的代码中使用:
And then use in your code:
Aggregation aggregation = newAggregation( new CutomAggregationOperation( new BasicDBObject( "$sample", new BasicDBObject( "size", 15 ) ) ) );
由于它实现了 AggregationOperation,因此它可以很好地与现有的管道操作辅助方法一起使用.即:
Since this implements AggregationOperation this works well with the exising pipeline operation helper methods. i.e:
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 中的类方法解释结果并正确获取您定义的 BS??ON 对象.
So again, everything is just a BSON Object at the end of the day. It's just a matter of having an interface wrapper so that the class methods in spring-mongo interpret the result and get your defined BSON Object correctly.