Spring Mongo存储库切片 [英] Spring mongo repository slice

查看:71
本文介绍了Spring Mongo存储库切片的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在MongoRepository中使用spring-sata-mongodb 1.8.2,并且尝试使用mongo $ slice选项限制查询时的列表大小,但是我在mongorepository中找不到此选项.

I am using spring-sata-mongodb 1.8.2 with MongoRepository and I am trying to use the mongo $slice option to limit a list size when query, but I can't find this option in the mongorepository.

我的课看起来像这样:

public class InnerField{
    public String a;
    public String b;
    public int n;
}

@Document(collection="Record")
punlic class Record{
    public ObjectId id;
    public List<InnerField> fields;
    public int numer;
}

如您所见,我有一个集合名称"Record",并且文档包含InnerField. InnerField列表一直在增长,所以我想在查询时限制所选字段的数量.

As you can see I have one collection name "Record" and the document contains the InnerField. the InnerField list is growing all the time so i want to limit the number of the selected fields when I am querying.

我看到了: https://docs.mongodb.org/v3.0/tutorial/project-fields-from-query-results/

这正是我所需要的,但是我在mongorepository中找不到相关的引用.

which is exactly what I need but I couldn't find the relevant reference in mongorepository.

有什么想法吗?

推荐答案

使用Java Mongo驱动程序提供的切片功能,并使用投影功能,如下面的代码所示.

Use slice functionality as provided in Java Mongo driver using projection as in below code.

例如:

List<Entity> list = new ArrayList<Entity>();
        // Return the last 10 weeks data only
FindIterable<Document> list = db.getDBCollection("COLLECTION").find()
                .projection(Projections.fields(Projections.slice("count", -10)));
MongoCursor<Document> doc = list.iterator();
while(doc.hasNext()){
    list.add(new Gson().fromJson(doc.next().toJson(), Entity.class));
}

上面的查询将获取所有Entity class类型的文档,每个Entity class文档的字段"列表将只有最后10条记录.

The above query will fetch all documents of type Entity class and the "field" list of each Entity class document will have only last 10 records.

这篇关于Spring Mongo存储库切片的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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