我可以使用此mongodb native query:
来完成此操作db.books.aggregate(
[ { $sample: { size: 15 } } ]
)
但如何在spring-data-mongodb
中完成?
答案 0 :(得分:7)
<强>更新强>
从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对象。
答案 1 :(得分:2)
Blakes Seven正确回答,但是,我希望提供更好的AggregationOperation实现,遵循标准的Spring 实施
import com.mongodb.BasicDBObject;
import com.mongodb.DBObject;
import org.springframework.data.mongodb.core.aggregation.AggregationOperation;
import org.springframework.data.mongodb.core.aggregation.AggregationOperationContext;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.util.Assert;
public class SampleOperation implements AggregationOperation {
private int size;
public SampleOperation(int size) {
Assert.isTrue(size > 0, " Size must be positive!");
this.size = size;
}
public AggregationOperation setSize(int size) {
Assert.isTrue(size > 0, " Size must be positive!");
this.size = size;
return this;
}
@Override
public DBObject toDBObject(AggregationOperationContext context) {
return new BasicDBObject("$sample", context.getMappedObject(Criteria.where("size").is(size).getCriteriaObject()));
}
}
之后,您可以使用构造函数创建SampleOperation对象,或稍后通过setSize()
方法更改它的大小,并照常将其应用于aggregate()
函数。
更新:在SpringBoot 2.0.0+和Spring Framework 5.0中:Spring Mongo删除DBObject
并替换为org.bson.Document
,因此最后的过去应该更新为:
@Override
public Document toDocument(AggregationOperationContext aggregationOperationContext) {
return new Document("$sample", aggregationOperationContext.getMappedObject(Criteria.where("size").is(size).getCriteriaObject()));
}
然后移除@Override toDBObject