来自MongoDB的随机文档使用spring-data [英] Random documents from MongoDB using spring-data

查看:417
本文介绍了来自MongoDB的随机文档使用spring-data的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我可以使用此 mongodb native query

db.books.aggregate(
   [ { $sample: { size: 15 } } ]
)

但如何在中执行此操作spring-data-mongodb

我在聚合类 spring-data / mongodb / docs / current / reference / html / #mongo.aggregationrel =nofollow> Spring Aggregation Framework

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 这适用于现有的管道操作辅助方法。 ie:

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中的类方法解释结果并正确获取定义的BSON对象。

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.

这篇关于来自MongoDB的随机文档使用spring-data的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆