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 results.
ApproachTo Perform a Find Operation With Sorting In MongoDB Using Node.js we will use the find method with a sort option on a MongoDB collection in Node.js. The sort option specifies the sorting criteria, enhancing query efficiency and results organization.
Syntax:db.collection.find(query).sort(sortSpecification) - The ‘query’ is an optional parameter that specifies the query conditions.
- The ‘sortSpecification’ is a JavaScript object that defines the fields to sort on and the sort order. The fields should be the name of the fields in the documents, and the value should be 1 for ascending order or -1 for descending order.
Steps to Set up Node AppStep 1: Create a Project folder
mkdir myapp Step 2: Move to the created project folder and initialize npm init
npm init -y Step 3: Install the necessary packages/libraries in your project using the following commands.
npm install mongoose express Project Structure:.png) The updated dependencies in package.json file will look like:
"dependencies": { "express": "^4.19.2", "mongoose": "^8.4.0" } Example: Implementation to perform a find operation with sorting in MongoDB using Node.js.
Node
//server.js
const express = require("express");
const mongoose = require("mongoose");
const app = express();
const port = 3000;
// Connect to MongoDB
mongoose
.connect("mongodb://localhost:27017/myapp")
.then(() => {
console.log("Connected successfully to MongoDB");
addData();
})
.catch((err) => {
console.error("Error occurred while connecting to MongoDB:", err);
});
// Define a schema
const Schema = mongoose.Schema;
const yourSchema = new Schema({
name: String,
age: Number,
// Add more fields as needed
});
// Define a model
const Student = mongoose.model("student", yourSchema);
const addData = async () => {
let data = [
{ name: "John", age: 30 },
{ name: "Alice", age: 25 },
{ name: "Bob", age: 35 },
{ name: "Eve", age: 28 },
{ name: "Michael", age: 40 },
{ name: "Sarah", age: 22 },
];
await Student.deleteMany();
await Student.insertMany(data);
console.log("Data inserted...")
}
// Define routes
app.get("/", async (req, res) => {
const data = await Student.find();
res.json(data);
})
app.get("/asd", (req, res) => {
// Perform a find operation with sorting
Student.find({})
.sort({ age: 1 })
.exec()
.then((docs) => {
res.json(docs);
})
.catch((err) => {
console.error("Error occurred:", err);
res.status(500).json({ error: "An error occurred" });
});
});
app.get("/desc", (req, res) => {
// Perform a find operation with sorting
Student.find({})
.sort({ age: -1 })
.exec()
.then((docs) => {
res.json(docs);
})
.catch((err) => {
console.error("Error occurred:", err);
res.status(500).json({ error: "An error occurred" });
});
});
app.listen(port, () => {
console.log(`Server is running on http://localhost:${port}`);
});
Step to Run Application: Run the application using the following command from the root directory of the project
npm start Output: Your project will be shown in the URL http://localhost:3000/
.png) Move to the below URL to see changes in ascending order
http://localhost:3000/asd .png) Move to the below URL to see changes in descending order
http://localhost:3000/desc .png) ConclusionPerforming a find operation with sorting in MongoDB using Node.js is straightforward. By following the steps outlined in this guide, you can easily connect to your MongoDB database, retrieve documents, and sort them as needed. This is a fundamental operation that you will frequently use in your MongoDB and Node.js applications.
|