Node.js MongoDB Sorting
MongoDB provides simple methods for deleting and sorting documents in a collection. When working with Node.js and MongoDB, you may need to remove records that are no longer required or sort query results based on a specific field.
In this tutorial, we will learn how to remove documents from a MongoDB collection using Node.js and how to sort MongoDB records in ascending and descending order.
Node.js MongoDB Remove
MongoDB allows you to delete documents from a collection based on a specified condition. Older MongoDB versions used the remove() method, but this method is deprecated in modern MongoDB drivers.
For new Node.js applications, you should use deleteOne() when you want to delete a single document or deleteMany() when you want to delete multiple matching documents.
Understanding the deleteMany() Method
The deleteMany() method accepts a query object that specifies which documents should be deleted.
For example, if you want to remove employees whose address is Ghaziabad, you can create the following query object:
const myquery = { address: "Ghaziabad" };
This query matches all documents where the address field contains the value Ghaziabad.
Example: Deleting Records Using Node.js
Let’s look at a practical example of deleting matching records from a MongoDB collection using Node.js.
Step 1: Create a JavaScript file named remove.js and add the following code:
const { MongoClient } = require("mongodb");
const url = "mongodb://localhost:27017";
const client = new MongoClient(url);
async function removeRecords() {
try {
await client.connect();
const db = client.db("MongoDatabase");
const myquery = { address: "Ghaziabad" };
const result = await db.collection("employees").deleteMany(myquery);
console.log(result.deletedCount + " record(s) deleted");
} catch (err) {
console.error(err);
} finally {
await client.close();
}
}
removeRecords();
Step 2: Run the File
After saving the file, open your command terminal and run:
node remove.js
If the MongoDB connection and deletion query are successful, the terminal will display the number of records deleted.
For example:
1 record(s) deleted
Step 3: Verify the Deletion
To verify the deletion, check the employees collection in MongoDB. Documents matching the condition { address: "Ghaziabad" } should no longer be present.
Node.js MongoDB Sorting
MongoDB provides the sort() method to arrange query results in ascending or descending order. You can specify the field you want to sort by and use 1 or -1 to define the sorting direction.
To sort documents in ascending order, use:
{ name: 1 }
To sort documents in descending order, use:
{ name: -1 }
Sort in Ascending Order
Let’s sort employee records in ascending order based on the name field.
Create a JavaScript file named sortasc.js and add the following code:
const { MongoClient } = require("mongodb");
const url = "mongodb://localhost:27017";
const client = new MongoClient(url);
async function sortAscending() {
try {
await client.connect();
const db = client.db("MongoDatabase");
const result = await db
.collection("employees")
.find()
.sort({ name: 1 })
.toArray();
console.log(result);
} catch (err) {
console.error(err);
} finally {
await client.close();
}
}
sortAscending();
Now run the file from your command terminal:
node sortasc.js
This will display the employee records sorted alphabetically from A to Z according to the name field.
Sort in Descending Order
More:- UPDATEGADH
You can also sort employee records in descending order using -1.
Create a JavaScript file named sortdsc.js and add the following code:
const { MongoClient } = require("mongodb");
const url = "mongodb://localhost:27017";
const client = new MongoClient(url);
async function sortDescending() {
try {
await client.connect();
const db = client.db("MongoDatabase");
const result = await db
.collection("employees")
.find()
.sort({ name: -1 })
.toArray();
console.log(result);
} catch (err) {
console.error(err);
} finally {
await client.close();
}
}
sortDescending();
Run the file using:
node sortdsc.js
This will return the employee records sorted in reverse alphabetical order from Z to A.
YT:- DecodeIT
Conclusion
MongoDB makes it easy to manage and organize documents when working with Node.js. The deleteOne() and deleteMany() methods can be used to remove documents based on specific conditions, while the sort() method allows query results to be arranged in ascending or descending order.
Understanding MongoDB deletion and sorting operations is useful when building Node.js applications that work with databases and need efficient CRUD operations.
Keywords: Node.js MongoDB remove, MongoDB deleteMany Node.js, MongoDB deleteOne Node.js, Node.js MongoDB sorting, MongoDB sort descending, MongoDB sort ascending, MongoDB sorting tutorial, Node.js MongoDB CRUD, Node.js MongoDB example, MongoDB sort query node js mongodb sorting example
node js mongodb sorting w3schools
node js mongodb sorting python
mongodb sort descending
mongodb compass sort by date
mongodb sort by date descending
mongodb sort query compass
mongodb sort array