0

I have the following mongo document representing website and links found on it.

 {"website":
     "id":"123456",
     "links":[
                 "link1","link2","link3",..."link1000"
                ]
 }

and I want to return a limited number of links from that specific document found by id, in order to support pagination, e.g. page=1, limit=100 should return first 100 links. I tried something like this, but it doesn't work. Is there any way I can limit the number of subdocuments?

 String query="{'website.id:'"+id+"'}";
 String fields="{links:1}";
 DBCursor dbCursor=this.getCollection(crawlersCollection)
      .find(this.query(query),this.query(fields)).skip(skip).limit(limit);

The other approach I tried is to use $slice

 String fields="{'links':{'$slice':["+skip+","+limit+"]}}";

but this doesn't work well, because it's not very useful for pagination. For example, if I have 43 links, page=2 with limit=100 will return 43 results, so I have to check the number of links before creating a query.

Do you have any suggestions how to solve this issue?

Thanks

1

1 Answer 1

2

The correct approach would be to use the $slice operator. To facilitate pagination you would have to change your method of determining "skip" and "limit".

For example, you could derive the "skip" value from page * limit, e.g. page 2 * limit 10 = skip 20. Then using the slice operator should work fine. If you're "skip" value goes beyond the array length then you'll get back an empty array in your results

Sign up to request clarification or add additional context in comments.

1 Comment

Thank you for suggestion. I made a mistake to pass the page number instead of skip value, and I always got a wrong results.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.