search

Home  >  Q&A  >  body text

I will have to use MongoDB to sort the data by page

I will have to sort the data based on date and pagination. This is the query I use: response.data =Waiting for distributorDoc.find().sort({"TimeStamp":-1,}); This is pagination: Pagination: { Total: 0, Number of pages: 0, Current page: page number, Per page: reqData.perPage || Count per page }

response.data =Waiting for distributorDoc.find().sort({"TimeStamp":-1,"perpage"==100});

P粉043566314P粉043566314484 days ago518

reply all(1)I'll reply

  • P粉338969567

    P粉3389695672023-09-12 00:32:16

    You can try using MongoDB's limit and skip methods.

    The limit() function in MongoDB is used to specify the maximum number of results to be returned.

    If you want to get a specific number of results after certain documents, you can use the skip() function.

    Sample Node JS code for pagination:

        function fetchDocs(pageNumber, nPerPage) {
            console.log('Page: ' + pageNumber);
            distributorDoc.find()
              .sort({'TimeStamp': -1})
              .skip(pageNumber > 0 ? ((pageNumber - 1) * nPerPage) : 0)
              .limit(nPerPage)
              .forEach(doc => {
                  console.log(doc);
              });
         }
    

    Read more here

    limit()

    skip()

    Check out this link for other alternatives

    Hope this is what you are looking for.

    reply
    0
  • Cancelreply