It is therefore important to understand various array operations in MongoDB and how we can use them in your databases.
For this post, we will focus on the MongoDB $pull operator. This operator allows you to remove a value from an existing array based on the specified condition.
Operator Syntax
The following form shows the operator syntax and parameter support:
The following behavior applies to the $pull operator in MongoDB documents:
- Defining the condition on array elements that embedded documents, the operator will apply the specified condition on each array element as a document collection.
- If the specified value is an array, the operator will only remove the elements in that match the specified value, order inclusive.
- If the value to be removed is a document, the operator will remove the elements with exact fields and values, order exclusive.
Let us explore the $pull operator in a practical environment.
Practical Example
Let us start by creating a test collection and add some sample documents. You can use the query as shown below:
{ ok: 1 }
Insert sample records.
{
_id: 1,
name: "William",
department: "Game Development",
startYear: 2021,
supported_langs: ["C++", "Java", "C#", "Python"],
technologies: [
{
"Docker": true,
"Level": "Intermediate"
},
{
"Ansible": true,
"Level": "Beginner"
}
],
country: "United States",
salary: 160000
}
])
Suppose we wish to remove “Python” from the supported_langs array, we can run a query as shown:
This should remove the “Python” entry from the supported_lang array. The resulting output is as shown:
"_id" : 1.0,
"name" : "William",
"department" : "Game Development",
"startYear" : 2021.0,
"supported_langs" : [
"C++",
"Java",
"C#"
],
"technologies" : [
{
"Docker" : true,
"Level" : "Intermediate"
},
{
"Ansible" : true,
"Level" : "Beginner"
}
],
"country" : "United States",
"salary" : 160000.0
}
We can see the entry “Python” has been removed from the document.
To remove an item from an array of documents, we can run a query as shown:
The command above will remove the item from the technologies array which contains two documents.
The resulting document is as shown:
Output:
"_id" :1.0,
"name" : "William",
"department" : "Game Development",
"startYear" : 2021.0,
"supported_langs" : [
"C++",
"Java",
"C#"
],
"technologies" : [
{
"Docker" : true,
"Level" : "Intermediate"
}
],
"country" : "United States",
"salary" : 160000.0
}
From the output above, we can verify the item with the specified parameter has been removed from the technologies array.
Conclusion
This article covers the fundamentals of working with the $pull operator in MongoDB, allowing you to remove items from an array in a given document.