How to Delete a Document From MongoDB Collection using NodeJS?
Last Updated : 04 Jun, 2024
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
JavaScript const { MongoClient } = require("mongodb"); const url = "mongodb://127.0.0.1:27017"; const dbName = "GeeksforGeeks"; 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:
Delete Document from CollectionExplanation:
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 GeeksforGeeks 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.
Similar Reads
How to Delete a Key from a MongoDB Document using Mongoose?
MongoDB is a popular NoSQL database that stores data in flexible, JSON-like documents. When working with MongoDB using Mongoose, a MongoDB object modeling tool designed to work in an asynchronous environment and developers encounter scenarios where they need to delete a key from a document. In this
6 min read
How To Get Data From 2 Different Collections Of MongoDB Using Node.js?
To retrieve data from two different collections in MongoDB using Node.js, we typically use the Mongoose library or the native MongoDB driver to establish a connection, query both collections and then combine or process the data as needed. This approach allows you to query multiple collections in par
4 min read
How to Insert a Document into a MongoDB Collection using Node.js?
MongoDB, a popular NoSQL database, offers flexibility and scalability for handling data. If you're developing a Node.js application and need to interact with MongoDB, one of the fundamental operations you'll perform is inserting a document into a collection. This article provides a step-by-step guid
5 min read
How to get Distinct Documents from MongoDB using Node.js ?
MongoDB is a cross-platform, document-oriented database that works on the concept of collections and documents. It stores data in the form of key-value pairs and is a NoSQL database program. The term NoSQL means non-relational. MongoDB module: This module of Node.js is used for connecting the Mongo
2 min read
How to drop collection in MongoDb using Node.js ?
MongoDB, the most popular NoSQL database, is an open-source document-oriented database. The term âNoSQLâ means ânon-relationalâ. It means that MongoDB isnât based on the table-like relational database structure but provides an altogether different mechanism for storage and retrieval of data. This fo
2 min read
How to Move MongoDB Document from one Collections to Another ?
Mongoose is an essential ODM (Object Data Modeling) library for MongoDB designed to work seamlessly with Node.js. It provides a structured way to define schemas, making it easier to interact with MongoDB collections. In this guide, we will cover the installation of Mongoose, the setup of schemas for
3 min read
How to delete single and multiple documents in MongoDB using node.js ?
MongoDB, the most popular NoSQL database is an open-source document-oriented database. The term âNoSQLâ means ânon-relationalâ. It means that MongoDB isnât based on the table-like relational database structure but provides an altogether different mechanism for storage and retrieval of data. This for
2 min read
How To Query For Documents In MongoDB Using NodeJS?
MongoDB is the popular NoSQL database that allows for flexible and scalable data storage. NodeJS and JavaScript runtime built on Chrome's V8 JavaScript engine. It is often used with MongoDB to build powerful and efficient applications. In this article, we will guide you on how to query the documents
4 min read
How to create new Collection in MongoDB using Node.js ?
MongoDB the most popular NoSQL database, is an open-source document-oriented database. The term âNoSQLâ means ânon-relationalâ. It means that MongoDB isnât based on the table-like relational database structure but provides an altogether different mechanism for storage and retrieval of data. This for
2 min read
How to Remove a Field Completely From a MongoDB Document?
In MongoDB, managing data is flexible and efficient, allowing developers to adapt to evolving application requirements easily. One common operation is removing fields from documents. Whether it's to Organize our data structure, improve performance or change business needs, MongoDB provides straightf
4 min read