Table of contents
1.
Introduction
2.
MongoDB
3.
Features of MongoDB
4.
MongoDB $pull Operator
5.
Syntax
5.1.
JavaScript
6.
Parameters
7.
Examples
7.1.
Step 1: Create a database
7.2.
Code
7.3.
JavaScript
7.3.1.
Output
7.4.
Explanation
7.5.
Step 2: Insert the values in the database
7.6.
Code
7.7.
JavaScript
7.7.1.
Output
7.8.
Explanation
7.9.
Step 3: Display the database
7.10.
Code
7.11.
JavaScript
7.11.1.
Output
7.12.
Explantation
7.13.
Step 4: a) Remove a skill from a student present in the database
7.14.
Code
7.15.
JavaScript
7.15.1.
Output
7.16.
Explanation
7.17.
Step 4: b) Remove a skill from all the students in the database
7.18.
Code
7.19.
JavaScript
7.19.1.
Output
7.20.
Explanation
7.21.
Step 4: c) Inserting more student information into the database
7.22.
Code
7.23.
JavaScript
7.23.1.
Output
7.24.
Explanation
7.25.
Step 4: d) Remove information from newly added student
7.26.
Code
7.27.
JavaScript
7.27.1.
Output
7.28.
Explanation
8.
Frequently Asked Questions
8.1.
Can numerous elements be removed from an array using the $pull operator?
8.2.
What happens if a field in a document is absent and you use the $pull operator on it?
8.3.
Can the $pull operator be combined with other update operators in a single MongoDB update operation?
8.4.
What occurs if none of the members in the array match the criterion of the $pull operator?
8.5.
Is deleting items from nested arrays in MongoDB documents feasible using the $pull operator?
9.
Conclusion
Last Updated: Mar 27, 2024
Easy

MongoDB $pull Operator

Author Vidhi Sareen
0 upvote
Career growth poll
Do you think IIT Guwahati certified course can help you in your career?

Introduction

Have you ever needed to remove a specific item from an array within your MongoDB documents? Here is where the $pull operator comes into the picture. It is a powerful tool in MongoDB that lets you extract elements from an array based on a specified condition.

MongoDB $pull Operator

This article will explore using the $pull operator to manipulate and manage your data.

MongoDB

MongoDB is an open-source database different from traditional ones because it stores data like JSON, a format many web apps use. It means instead of tables, it has flexible 'documents' with various fields. One of its significant advantages is that it can quickly expand across multiple servers as more data comes in. 

MongoDB

You can search it quickly, do fancy data tricks like grouping or averaging, and even handle location-based data. Developers love MongoDB mainly because it's adaptable to changes, scales well with growth, and fits nicely with how many modern apps operate on data. Plus, there's a big community around it, offering lots of tools and support.

Features of MongoDB

There are many features of MongoDB, such as:

  • MongoDB is a well-known NoSQL database, making it adaptable to many data types because it is built to manage unstructured and semi-structured data.
     
  • MongoDB stores information in documents that resemble JSON, which makes it simple to deal with data in a fashion that mirrors the organization of your application.
     
  • MongoDB does not require an existing schema to store data because it is model-less. Fields can be quickly added or removed.
     
  • MongoDB can handle heavy traffic and vast data by horizontal scaling through sharding.

MongoDB $pull Operator

The MongoDB $pull operator is a tool that removes specific items from an array inside a document. Think of it like picking out certain fruits from a fruit basket based on your choice. 

Imagine you have a classroom list with student names and want to remove the student named "Ninja_1" from it. By using the $pull operator, you can easily do this. For example, if you maintain a list like ["Ninja_1", "Ninja_2", "Ninja_3"] and you use $pull to remove "Ninja_1", the list then becomes ["Ninja_2", "Ninja_3"]. It's easy to change your list without going through it individually.

Syntax

The syntax of MongoDB $pull Operator is as follows:

  • JavaScript

JavaScript

db.collection.update(
  { },
  { $pull: { <field1>: <value|condition>, ... } },
  { multi: true }
)
You can also try this code with Online Javascript Compiler
Run Code

Parameters

The parameters of MongoDB $pull Operator are as follows:

  • <field1>: the name of the array field you want to pull from.
     
  • <value|condition>: the value or condition specifying which elements to remove.
     
  • The multi: true option is to update multiple documents.

Examples

In this section, we will learn about the $pull Operator with different examples. To run the following code you need to install MongoDB into your system. Open your MongoDB shell and run the following commands.

Step 1: Create a database

Create a database using the following command.

Code

  • JavaScript

JavaScript

use codingNinjaDB
You can also try this code with Online Javascript Compiler
Run Code

Output

output

Explanation

We have created a database using the above command and named it ‘CodingNinjaDB’.

Step 2: Insert the values in the database

Insert the values in the database using the following command.

Code

  • JavaScript

JavaScript

// Insert a NinjaA student information
codingNinjaDB> db.ninjas.insertOne({
... "name": "NinjaA",
... "skills": ["stealth", "javascript", "python"]
... });

// Insert a NinjaB student information
codingNinjaDB> db.ninjas.insertOne({
... "name": "NinjaB",
... "skills": ["python", "mongodb", "stealth"]
... });

// Insert a NinjaC student information
codingNinjaDB> db.ninjas.insertOne({
... "name": "NinjaC",
... "skills": ["java", "mongodb", "c++"]
... });
You can also try this code with Online Javascript Compiler
Run Code

Output

output

Explanation

We're working with a MongoDB database named codingNinjaDB in the given code. Within this database, we're adding entries to a collection called ninjas. Each entry describes a ninja and lists their skills. For example, the first ninja, ‘NinjaA’, has stealthJavaScript, and Python skills. After adding each entry, the database acknowledges the successful addition and provides a unique identifier for each ninja's details, much like a page number.

Step 3: Display the database

As we have inserted the values in the database, check whether the insertion is successful.

Code

  • JavaScript

JavaScript

db.ninjas.find().pretty()
You can also try this code with Online Javascript Compiler
Run Code

Output

output

Explantation

The ninjas collection uses the find() method to retrieve all the entries (or documents). The following pretty() function formats the results to present them in an easy-to-read manner.

Step 4: a) Remove a skill from a student present in the database

Now, we will update the database by removing a skill of ‘NinjaA’ in this database and display the output.

Code

  • JavaScript

JavaScript

// Updating NinjaA’s skills by removing “stealth” 
codingNinjaDB> db.ninjas.update(
... { "name": "NinjaA" },
... { $pull: { "skills": "stealth" } }
... )

// Display the updated database
codingNinjaDB> db.ninjas.find({ "name": "NinjaA" }).pretty()
You can also try this code with Online Javascript Compiler
Run Code

Output

output

Explanation

In the code, we're updating NinjaA's info in the codingNinjaDB database. We're taking away the 'stealth' skill from NinjaA. After doing that, we're checking NinjaA's new details to see the updates we made.

Step 4: b) Remove a skill from all the students in the database

In this code, we will remove a skill from all the students present in the database.

Code

  • JavaScript

JavaScript

// Updating the information of the document by removing the skill “javascript”
codingNinjaDB> db.ninjas.updateMany(
... { "skills": "javascript" },
... { $pull: { "skills": "javascript" } }
... )

// Display the updated database
codingNinjaDB> db.ninjas.find().pretty()
You can also try this code with Online Javascript Compiler
Run Code

Output

output

Explanation

In the given code, we're accessing the codingNinjaDB database and making changes to multiple ninjas simultaneously. We're targeting all ninjas that list "javascript" as one of their skills and removing that particular skill from their profiles. So, after this action, any ninja who previously had "javascript" won't have it anymore.

Step 4: c) Inserting more student information into the database

In this, we are adding two more pieces of information for the students.

Code

  • JavaScript

JavaScript

// Insert a NinjaD student information
codingNinjaDB> db.ninjas.insertOne({
... "name": "NinjaD",
... "missions": [
... { "title": "Retrieve Data", "status": "completed" },
... { "title": "Fix Bug", "status": "in-progress" }
... ]
... });

// Insert a NinjaE student information
codingNinjaDB> db.ninjas.insertOne({
... "name": "NinjaE",
... "missions": [
... { "title": "Develop App", "status": "completed" },
... { "title": "Fix Bug", "status": "in-progress" },
... { "title": "Database Migration", "status": "completed" }
... ]
... });
You can also try this code with Online Javascript Compiler
Run Code

Output

output

Explanation

In the provided code, we're adding information to the codingNinjaDB database about two ninjas, NinjaD and NinjaE. We're recording two missions for NinjaD: "Retrieve Data," which he has already completed, and "Fix Bug," which he is still working on. On the other hand, NinjaE has three missions: "Develop App" and "Database Migration" are both completed, while "Fix Bug" is ongoing.

Step 4: d) Remove information from newly added student

In this, we are removing information for the newly added student.

Code

  • JavaScript

JavaScript

codingNinjaDB> db.ninjas.update(
... { "name": "NinjaE" },
... { $pull: { "missions": { "status": "completed" } } }
... )

codingNinjaDB> db.ninjas.find().pretty()
You can also try this code with Online Javascript Compiler
Run Code

Output

output
output

Explanation

In the given code, we're accessing the codingNinjaDB database and changing NinjaE's profile in the ninja's collection. We aim to identify all of NinjaE's missions marked as "completed" and remove them from his list of missions. After this action, NinjaE's profile will no longer display any missions he has already completed.

Frequently Asked Questions

Can numerous elements be removed from an array using the $pull operator?

The $pull operator does indeed allow for removing several elements from an array all at once. If more than one array member meets the necessary criterion, they are all eliminated from the array.

What happens if a field in a document is absent and you use the $pull operator on it?

The $pull operator will not cause MongoDB to throw an error if you use it on a field that does not exist in the document. Instead of making any changes, it will handle the field like an empty array.

Can the $pull operator be combined with other update operators in a single MongoDB update operation?

In a single update operation, you can combine the $pull operator with other update operators like $set, $inc, or $push. It allows you to make numerous edits to a document at once.

What occurs if none of the members in the array match the criterion of the $pull operator?

The array does not change if the condition of the $pull operator does not match any entries in the array. The file will be up-to-date without changing the array, and MongoDB won't give an error.

Is deleting items from nested arrays in MongoDB documents feasible using the $pull operator?

You may remove elements from nested arrays in MongoDB documents using the $pull operator. To remove elements from nested arrays, you must give the path to the nested array in your $pull operation.

Conclusion

In this article, we learn about MongoDB $pull Operator. We examine MongoDB and its features in detail. We even explore MongoDB $pull Operator examples with various use cases. We operate the $pull operator to remove some information from the created database, like removing a skill from a particular student or a skill from all the students' data.

Do check out the link to learn more about such a topic

You can find more informative articles or blogs on our platform. You can also practice more coding problems and prepare for interview questions from well-known companies on your platform, Coding Ninjas Studio.

Live masterclass