Spring mongo repository slice

强颜欢笑 提交于 2019-12-02 09:31:58

Providing an abstraction for the $slice operator in Query is still an open issue. Please vote for DATAMONGO-1230 and help us prioritize.

For now you still can fall back to using BasicQuery.

String qry = "{ \"_id\" : \"record-id\"}";
String fields = "{\"fields\": { \"$slice\": 2} }";

BasicQuery query = new BasicQuery(qry, fields);

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

For Example:

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));
}

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.

I found in unit test file (DATAMONGO-1457) way to use slice. Some thing like this.

newAggregation(
    UserWithLikes.class, 
    match(new Criteria()),
    project().and("likes").slice(2)
);
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!