Spring mongo 存储库切片

我正在将 spring-sata-mongodb 1.8.2 与 MongoRepository 一起使用,并且我尝试在查询时使用 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));
}

上述查询将获取所有实体类类型的文档,并且每个实体类文档的字段"列表将只有最后 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.

相关文章