MongoDB / CRUD Operations in MongoDB

Deleting Documents in MongoDB

This tutorial covers how to delete documents in MongoDB. You will learn how to remove data from your database, using both the deleteOne and deleteMany methods.

Tutorial 4 of 5 5 resources in this section

Section overview

5 resources

Explores how to create, read, update, and delete documents in MongoDB.

Deleting Documents in MongoDB

1. Introduction

In this tutorial, we will focus on how to delete documents in MongoDB. MongoDB is a popular NoSQL database that stores data in BSON format, which is a binary representation of JSON-like documents. Deleting documents is a crucial part of data management, and MongoDB provides two primary methods for this purpose: deleteOne() and deleteMany().

By the end of this tutorial, you will learn:

  • How to use the deleteOne() method to delete a single document.
  • How to use the deleteMany() method to delete multiple documents.
  • Best practices when deleting documents.

There are no strict prerequisites for this tutorial, but it would be helpful if you have:

  • Basic knowledge of MongoDB.
  • MongoDB installed on your local machine.
  • Basic knowledge of JavaScript, as we'll use it in our examples.

2. Step-by-Step Guide

In MongoDB, the deleteOne() function is used to delete the first document that matches the deletion criteria, while deleteMany() is used to delete all documents that match the deletion criteria.

2.1 deleteOne()

The deleteOne() function deletes the first document that matches a specified filter. Here's how it's used:

db.collection.deleteOne(query)

The query parameter is a filter that specifies the document to delete.

2.2 deleteMany()

The deleteMany() function deletes all documents that match a specified filter. Here's how it's used:

db.collection.deleteMany(query)

The query parameter is a filter that specifies the documents to delete.

3. Code Examples

Example 1: Using deleteOne()

In the following example, we'll delete a single document from the employees collection where name is 'John Doe':

// This is your MongoDB client
const MongoClient = require('mongodb').MongoClient;

// This is your connection string
const url = 'mongodb://localhost:27017/';

// Connect to the server
MongoClient.connect(url, function(err, db) {
  if (err) throw err;

  // This is your database
  const dbo = db.db('mydb');

  // This is your query
  const myquery = { name: 'John Doe' };

  // This is where you're deleting one document
  dbo.collection('employees').deleteOne(myquery, function(err, obj) {
    if (err) throw err;
    console.log('1 document deleted');
    db.close();
  });
});

Example 2: Using deleteMany()

In the following example, we'll delete all documents from the employees collection where name starts with the letter 'A':

// This is your MongoDB client
const MongoClient = require('mongodb').MongoClient;

// This is your connection string
const url = 'mongodb://localhost:27017/';

// Connect to the server
MongoClient.connect(url, function(err, db) {
  if (err) throw err;

  // This is your database
  const dbo = db.db('mydb');

  // This is your query
  const myquery = { name: /^A/ };

  // This is where you're deleting many documents
  dbo.collection('employees').deleteMany(myquery, function(err, obj) {
    if (err) throw err;
    console.log(obj.result.n + ' document(s) deleted');
    db.close();
  });
});

4. Summary

In this tutorial, we covered how to delete documents in MongoDB using deleteOne() and deleteMany(). We also walked through examples of how to use these methods.

Next, you might want to learn about other CRUD operations (Create, Update, Read) in MongoDB.

Here are a few additional resources:

5. Practice Exercises

Exercise 1: Delete a document from the students collection where age is less than 20.

Exercise 2: Delete all documents from the employees collection where salary is greater than 50000.

Exercise 3: Delete all documents from the products collection where name starts with the letter 'B'.

Practice is key to mastering any concept. Try to solve these exercises, and don't forget to check the MongoDB documentation if you're stuck. Happy learning!

Need Help Implementing This?

We build custom systems, plugins, and scalable infrastructure.

Discuss Your Project

Related topics

Keep learning with adjacent tracks.

View category

HTML

Learn the fundamental building blocks of the web using HTML.

Explore

CSS

Master CSS to style and format web pages effectively.

Explore

JavaScript

Learn JavaScript to add interactivity and dynamic behavior to web pages.

Explore

Python

Explore Python for web development, data analysis, and automation.

Explore

SQL

Learn SQL to manage and query relational databases.

Explore

PHP

Master PHP to build dynamic and secure web applications.

Explore

Popular tools

Helpful utilities for quick tasks.

Browse tools

Interest/EMI Calculator

Calculate interest and EMI for loans and investments.

Use tool

WHOIS Lookup Tool

Get domain and IP details with WHOIS lookup.

Use tool

Scientific Calculator

Perform advanced math operations.

Use tool

Text Diff Checker

Compare two pieces of text to find differences.

Use tool

Lorem Ipsum Generator

Generate placeholder text for web design and mockups.

Use tool

Latest articles

Fresh insights from the CodiWiki team.

Visit blog

AI in Drug Discovery: Accelerating Medical Breakthroughs

In the rapidly evolving landscape of healthcare and pharmaceuticals, Artificial Intelligence (AI) in drug dis…

Read article

AI in Retail: Personalized Shopping and Inventory Management

In the rapidly evolving retail landscape, the integration of Artificial Intelligence (AI) is revolutionizing …

Read article

AI in Public Safety: Predictive Policing and Crime Prevention

In the realm of public safety, the integration of Artificial Intelligence (AI) stands as a beacon of innovati…

Read article

AI in Mental Health: Assisting with Therapy and Diagnostics

In the realm of mental health, the integration of Artificial Intelligence (AI) stands as a beacon of hope and…

Read article

AI in Legal Compliance: Ensuring Regulatory Adherence

In an era where technology continually reshapes the boundaries of industries, Artificial Intelligence (AI) in…

Read article

Need help implementing this?

Get senior engineering support to ship it cleanly and on time.

Get Implementation Help