Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
How to remove array element in MongoDB?
To remove array elements in MongoDB, you can use the $pull operator along with $in for multiple values or direct value matching. The $pull operator removes all instances of a value or values that match a specified condition from an existing array.
Syntax
db.yourCollectionName.update({},
{$pull:{yourFirstArrayName:{$in:["yourValue"]},yourSecondArrayName:"yourValue"}},
{multi:true}
);
Sample Data
Let us create a collection with a document to understand the concept better ?
db.removeArrayElement.insertOne({
"StudentName":"Larry",
"StudentCoreSubject":["MongoDB","MySQL","SQL Server","Java"],
"StudentFavouriteTeacher":["John","Marry","Carol"]
});
{
"acknowledged" : true,
"insertedId" : ObjectId("5c6ec9c46fd07954a4890688")
}
Display all documents from the collection with the help of find() method ?
db.removeArrayElement.find().pretty();
{
"_id" : ObjectId("5c6ec9c46fd07954a4890688"),
"StudentName" : "Larry",
"StudentCoreSubject" : [
"MongoDB",
"MySQL",
"SQL Server",
"Java"
],
"StudentFavouriteTeacher" : [
"John",
"Marry",
"Carol"
]
}
Removing Array Elements
Here is the query to remove array elements from multiple arrays in a single operation ?
db.removeArrayElement.update({},
{$pull:{StudentCoreSubject:{$in:["Java"]},StudentFavouriteTeacher:"Marry"}},
{multi:true}
);
WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })
This query removes "Java" element from the first array ("StudentCoreSubject") and "Marry" element from the second array ("StudentFavouriteTeacher").
Verify Results
Let us display documents from the collection once again to check if the elements have been removed ?
db.removeArrayElement.find().pretty();
{
"_id" : ObjectId("5c6ec9c46fd07954a4890688"),
"StudentName" : "Larry",
"StudentCoreSubject" : [
"MongoDB",
"MySQL",
"SQL Server"
],
"StudentFavouriteTeacher" : [
"John",
"Carol"
]
}
Looking at the output above, there is no "Java" element in the first array ("StudentCoreSubject") and no "Marry" element in the second array ("StudentFavouriteTeacher").
Key Points
- Use
$inoperator when removing multiple values from an array - Use direct value matching when removing a single specific value
- The
multi:trueoption ensures the operation applies to all matching documents
Conclusion
The $pull operator effectively removes array elements in MongoDB by matching specific values or using conditions with $in. This approach allows you to clean up arrays by removing unwanted elements across multiple fields in a single operation.
