Spring mongo repository slice

前端 未结 3 721
无人共我
无人共我 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:55

    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);
    
    0 讨论(0)
  • 2021-01-16 20:56

    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.

    0 讨论(0)
  • 2021-01-16 20:57

    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)
    );
    
    0 讨论(0)
提交回复
热议问题