डिप्लोमा इन ऑफिस मैनेजमेंट एण्ड अकाउटिंग

डिप्लोमा इन ऑफिस मैनेजमेंट एण्ड अकाउटिंग

Full Stack Web Development with Laravel

Full Stack Web Development with Laravel

Affiliate Program

Affiliate Program

simple example to create pagination with skip and limit in mongodb

const MongoClient = require('mongodb').MongoClient;
const url = 'mongodb://localhost:27017';
const dbName = 'school';
const client = new MongoClient(url, { useUnifiedTopology: true });

// Connect to MongoDB
client.connect(function(err) {
  if (err) throw err;

  const db = client.db(dbName);
  const collection = db.collection('students');

  // Set the page number and page size
  const pageNumber = 1; // The first page
  const pageSize = 10; // The number of documents to retrieve per page

  // Calculate the number of documents to skip based on the page size and page number
  const skip = (pageNumber - 1) * pageSize;

  // Query the collection with skip and limit to retrieve a page of documents
  collection.find().skip(skip).limit(pageSize).toArray(function(err, docs) {
    if (err) throw err;

    console.log(`Retrieved ${docs.length} documents for page ${pageNumber}`);

    // Close the MongoDB connection
    client.close();
  });
});
 
 
In this example, we first connect to the school database and the students collection using the MongoDB Node.js driver.
 
Next, we set the pageNumber and pageSize variables to specify the page number and the number of documents to retrieve per page, respectively.
 
Then, we calculate the number of documents to skip based on the page number and page size using the formula (pageNumber - 1) * pageSize.
 
Finally, we use the find() method on the collection object to retrieve a page of documents using the skip() and limit() methods. The skip() method skips the specified number of documents, and the limit() method limits the number of documents to retrieve to the specified value.
 
We then convert the results to an array using the toArray() method and log the number of retrieved documents for the specified page.
 
Note that this is just a basic example of how to create pagination with skip and limit in MongoDB. In practice, you may need to add additional query criteria, sorting, or filtering to your queries to retrieve the desired results.
© 2016 - 2023, All Rights are Reserved.