Spring mongo repository slice

前端 未结 3 742
无人共我
无人共我 2021-01-16 19:56

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 th

3条回答
  •  暗喜
    暗喜 (楼主)
    2021-01-16 20:56

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

    For Example:

    List list = new ArrayList();
            // Return the last 10 weeks data only
    FindIterable list = db.getDBCollection("COLLECTION").find()
                    .projection(Projections.fields(Projections.slice("count", -10)));
    MongoCursor 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.

提交回复
热议问题