How to Perform a Find Operation with Limit and Skip in MongoDB using Node.js?
In MongoDB, the find operation is used to query the database and retrieve documents that match a specified criterion. Using limit and skip along with find allows for efficient pagination of results. limit specifies the maximum number of documents to return, while skip specifies the number of documents to skip from the start of the result set.
There are various ways to implement a find operation with limit and skip in MongoDB using Node.js. We will discuss the most common method using the MongoDB Node.js Driver.
Using MongoDB Node.js Driver
The MongoDB Node.js Driver provides a straightforward API to interact with the database. Here’s how you can use it to perform a find operation with limit and skip.
Steps to Create a NodeJS App and Installing Module
Step 1: Initialize a Node.js Application using the below command:
mkdir mongodb-pagination
cd mongodb-pagination
npm init -y
Step 2: Install Required Modules using the below command:
npm install mongodb
Project Structure:
The Updated Dependencies in your package.json File is look like:
"dependencies": {
"mongodb": "^6.6.2"
}
Explanation
- Connect to MongoDB: Use the MongoDB connection string to connect to your database.
- Insert Sample Data: Before performing the query, we insert sample data into the sample_collection.
- Find Operation with Limit and Skip:
- The query object is empty, meaning it will match all documents in the collection.
- The options object includes skip and limit to control the results returned.
- The find method returns a cursor, and toArray converts the cursor to an array of documents.
Example: Create an index.js file in the root of your project directory:
const { MongoClient } = require("mongodb");
async function run() {
const uri = "mongodb://localhost:27017";
const client = new MongoClient(uri);
try {
await client.connect();
const database = client.db("sample_database");
const collection = database.collection("sample_collection");
// Insert sample data
const sampleData = [
{ name: "GFG1", age: 25 },
{ name: "GFG2", age: 30 },
{ name: "GFG3", age: 35 },
{ name: "GFG4", age: 40 },
{ name: "GFG5", age: 45 },
{ name: "GFG6", age: 50 },
{ name: "GFG7", age: 55 },
{ name: "GFG8", age: 60 },
{ name: "GFG9", age: 65 },
{ name: "GFG10", age: 70 },
];
// Ensure the collection is empty before inserting
await collection.deleteMany({});
await collection.insertMany(sampleData);
// Define the query and options
// Define your query here, {} means select all documents
const query = {};
const options = {
skip: 2, // Skip the first 2 documents
limit: 5, // Limit the result to 5 documents
};
const cursor = collection.find(query, options);
const results = await cursor.toArray();
console.log("Results:", results);
} finally {
await client.close();
}
}
run().catch(console.dir);
Start your server using the following command:
node index.js
Output:
Contact Us