0

I am building a C# ASP.net core web application which connects to MongoDB. My aim is to get data from MongoDB in form of pages, for example if I have 100 documents of a certain collection I would like to get 10 documents after ID=X and 10 documents before ID=X.

What is the right syntax to get data like that knowing ID of a document (Previous 10 documents as well as Next 10 documents)?

mason
  • 31,774
  • 10
  • 77
  • 121
mohamed elsabagh
  • 352
  • 3
  • 16
  • That's too broad. You've got two tasks 1) implement infinite scrolling and 2) getting paged data from your database. Neither of which is a valid question for SO. Look up how to do it. Try to implement your own code. If you get stuck on a specific part, that'd be a more appropriate question. Make sure you provide an [MCVE](http://stackoverflow.com/help/mcve). – mason Mar 09 '17 at 14:29
  • I am just asking about the syntax to get next 10 documents and previous 10 documents for example from mongodb C# driver – mohamed elsabagh Mar 09 '17 at 14:32
  • "Just"? Read your question again: "My main problem is I am expecting the collection will hold hundreds of records.....so I want data is fetched while scrolling down from client side." You also tagged your question as [REST](http://stackoverflow.com/tags/rest/info). – mason Mar 09 '17 at 14:33
  • Ok I will edit the question now for better understanding – mohamed elsabagh Mar 09 '17 at 14:34
  • Possible duplicate of [MongoDB - paging](http://stackoverflow.com/questions/5049992/mongodb-paging) – mason Mar 09 '17 at 14:37
  • Also see [this question](http://stackoverflow.com/questions/5049992/mongodb-paging). – mason Mar 09 '17 at 14:38
  • I have retagged your question appropriately. In the future, please consider what is actually relevant to the question when you're tagging it, this will make sure the appropriate people can find it to answer and help others with similar issues find your question. – mason Mar 09 '17 at 14:42
  • ok Thanks so much, I am sorry for that. I will check the posts you mentioned – mohamed elsabagh Mar 09 '17 at 14:43

1 Answers1

1

You have to execute 2 queries:

1) for the next 10 objects

db.collection.find({_id:{$gt:object_id}}).limit(10)

2) for the previous 10 objects

db.collection.find({_id:{$lte:object_id}}).sort({_id:-1}).limit(10)

When you sort with _id, you will get the documents sorted (descending or ascending) by their creation timestamps.

Moi Syme
  • 466
  • 2
  • 8