How to Delete a Document From MongoDB Collection using NodeJS?
MongoDB, the most popular NoSQL database, is an open-source document-oriented database. The term ‘NoSQL’ means ‘non-relational’. This means that MongoDB isn’t based on a table-like relational database structure but provides an altogether different mechanism for data storage and retrieval. This storage format is called BSON ( similar to JSON format).
In this article, we will learn how to delete documents, starting from connecting MongoDB to NodeJS, creating a collection, and inserting the documents inside it.
Step to Delete a Document from a MongoDB collection using Nodejs
Step 1: Create A Node Project
Initially set up a Nodejs Project using the following command.
npm init
or
npm init -y
- The npm init command asks some setup questions that are important for the project
- npm init -y command is used to set all the answers to the setup questions as yes.
Step 2: Install the MongoDB package
npm install mongodb
or
npm i mongodb
You can verify the installation using following command in the integrated terminal of IDE.
mongodb --version
NodeJS and MongoDB Connection
Once the MongoDB is installed we can use MongoDB database with the Node.js project. Initially we need to specify the database name, connection URL and the instance of MongoDBClient.
const { MongoClient } = require('mongodb');
// or as an ECMAScript module:
// import { MongoClient } from 'mongodb'
// Connection URL
const url = 'mongodb://localhost:27017';
const client = new MongoClient(url);
// Database Name
const dbName = 'database_name';
async function main() {
// Use connect method to connect to the server
await client.connect();
console.log('Connected successfully to server');
//Can Add the CRUD operations
}
main() .then(console.log)
.catch(console.error)
.finally(() => client.close());
- MongoClient is a class that is used to connect MongoDB and Nodejs.
CRUD Operations in MongoDB
We can perform the basic Create, Read, Update and Delete Operations on Collections in MongoDB.
Create a Collection in MongoDb using Node.js
In this operation we create a collection inside a database.Intilally we specify the database in which collections is to be created.
const dbName = 'database_name'; //Sepcify Database
await client.connect(); //Connect to db
const collection = db.collection('collection_name'); //Create Collection
const doc_array = [
{document1 },
{document2 },
{ document3 },
];
const insertDoc = await collection.insertMany( doc_array ); //Insert into collection
console.log('Inserted documents =>', insertDoc);
Add the above code in the main() function as mentioned above
- doc_array contains the three documents .
- Documents are inserted into the collection using the insertMany() function.
Read Operation
We can read the documents inside the collection using the find() method.
const doc = await collection.find({}).toArray();
console.log('Found documents =>', doc );
- find() method is used to along with empty {} are used to read all the documents in the collection.Which are further converted into the array using the toArray() method.
Update Operation
To update the documents we can use updateOne() or updateMany methods.
Syntax of update() method
db.collection_name.update( query, update, optional)
- query is used to filter out the documents which are to be updated
- update is to update the values of the fields int the document.
- optional parameter contains the upsert ,multi, writeConcern, collation, arrayFilters field which are use according to conditions.
const updateDoc = await collection.updateOne(
{ rolNo : 103 },
{ $set: { favSub: " Geography " } }
);
console.log('Updated documents =>', updateDoc);
Deleting Documents
The delete operation are used to delete or remove the documents from a collection. You can perform delete operations using the deleteOne() method and deleteMany() method
const deleteDoc= await collection.deleteMany({
favSub: "Maths"
});
console.log('Deleted documents =>', deleteDoc);
Example
const { MongoClient } = require("mongodb");
const url = "mongodb://127.0.0.1:27017";
const dbName = "w3wiki";
const studentsData = [
{ rollno: 101, Name: "Raj ", favSub: "Math" },
{ rollno: 102, Name: "Yash", favSub: "Science" },
{ rollno: 103, Name: "Jay", favSub: "History" },
];
// Connection
MongoClient.connect(url)
.then(async (client) => {
console.log("Connected successfully to MongoDB");
const db = client.db(dbName);
const collection = db.collection("students");
try {
// Add students to the database
await collection.insertMany(studentsData);
console.log("Three students added successfully");
// Query all students from the database
const students = await collection.find().toArray();
console.log("All students:", students);
// Delete the 3rd Document
const deleteDoc = await collection.deleteOne({ rollno: 103 });
const students1 = await collection.find().toArray();
console.log("After Deleting the 3rd Document :", students1);
} catch (err) {
console.error("Error :", err);
} finally {
// Close the connection when done
client.close();
}
})
.catch((err) => {
console.error("Error connecting to MongoDB:", err);
});
Output:
Explanation:
In the above example , MongoDB and Nodejs connection is set up connection using the MongoClient class .MongoClient.connect(url) returns a promise which resolves a client object if the database is connected successfully.
As the connection is set up the w3wiki database and the students collection is created and 3 documents are inserted into the collection using insertMany() method .After inserting the documents the 3rd document is deleted using the deleteOne() method.