Ask Your Question
0

How can I implement pagination while sorting data in mongodb?

asked 2022-02-24 11:00:00 +0000

scrum gravatar image

edit retag flag offensive close merge delete

1 Answer

Sort by ยป oldest newest most voted
0

answered 2021-10-04 10:00:00 +0000

lalupa gravatar image

To implement pagination while sorting data in MongoDB, you can use the skip() and limit() methods together with the sort() method.

Here's an example:

const perPage = 10; // number of items to display per page
const pageNumber = 1; // current page number

const sortOrder = { timestamp: -1 }; // sort by timestamp in descending order

const items = await db.collection('my_collection')
  .find({})
  .sort(sortOrder)
  .skip((pageNumber - 1) * perPage) // skip items from previous pages
  .limit(perPage) // display only the items for the current page
  .toArray();

console.log(items);

In this example, we're sorting the data by the timestamp field in descending order, skipping the items from previous pages, and limiting the number of items to display per page using the skip() and limit() methods. We're also using the toArray() method to get the array of documents.

To implement pagination, you need to modify the pageNumber variable accordingly, based on the user's input or the current page number.

edit flag offensive delete link more

Your Answer

Please start posting anonymously - your entry will be published after you log in or create a new account. This space is reserved only for answers. If you would like to engage in a discussion, please instead post a comment under the question or an answer that you would like to discuss

Add Answer


Question Tools

Stats

Asked: 2022-02-24 11:00:00 +0000

Seen: 9 times

Last updated: Oct 04 '21