How to Perform a Find Operation with Limit and Skip in MongoDB using Node.js?
Last Updated :
27 May, 2024
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:
Project StructureThe 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:
JavaScript
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:
To perform a find operation with limit and skip in MongoDB using Node.js
Similar Reads
How To Perform a Find Operation With Sorting In MongoDB Using Node.js? Performing a find operation with sorting in MongoDB using Node.js is a common task for developers working with databases. This guide will walk you through the process step-by-step, including setting up a MongoDB database, connecting to it using Node.js, performing a find operation, and sorting the r
3 min read
How to Perform a findOne Operation in MongoDB using Node.js? The findOne operation in MongoDB is used to get a single document from the collection if the given query matches the collection record. While using findOne, if more than one record is there with the exact same match, then it will return the very first one. We will use this operation if we need to fe
4 min read
How to Perform Find Operation With Projection in MongoDB Using NodeJS? MongoDB's find() method can be used to query the documents from the collection. Protection in MongoDB allows you to select the fields to return in the query results which can be useful for improving the performance and reducing the amount of the data transferred over the network. In this article, we
5 min read
How to Perform Aggregation Operations in MongoDB using Node.js? Aggregation operations in MongoDB allow you to process data records and return computed results. These operations group values from multiple documents, and perform a variety of operations on the grouped data to return a single result. MongoDB's aggregation framework is powerful and flexible, enablin
3 min read
How to Create Pagination in Node.js using Skip and Limit ? Creating pagination in Node.js using the skip and limit methods. This approach efficiently retrieves specific data subsets from a database, improving performance and user experience by loading content in manageable segments rather than all at once. What is Pagination?Pagination is a very helpful met
4 min read