Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • NodeJS Tutorial
  • NodeJS Exercises
  • NodeJS Assert
  • NodeJS Buffer
  • NodeJS Console
  • NodeJS Crypto
  • NodeJS DNS
  • NodeJS File System
  • NodeJS Globals
  • NodeJS HTTP
  • NodeJS HTTP2
  • NodeJS OS
  • NodeJS Path
  • NodeJS Process
  • NodeJS Query String
  • NodeJS Stream
  • NodeJS String Decoder
  • NodeJS Timers
  • NodeJS URL
  • NodeJS Interview Questions
  • NodeJS Questions
  • Web Technology
Open In App
Next Article:
How to get Distinct Documents from MongoDB using Node.js ?
Next article icon

How to Delete a Document From MongoDB Collection using NodeJS?

Last Updated : 04 Jun, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

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-Collection
Delete Document from Collection

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 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.


Next Article
How to get Distinct Documents from MongoDB using Node.js ?

P

pritamvinodfulari
Improve
Article Tags :
  • Web Technologies
  • Node.js
  • MongoDB

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
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences