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 do you remove an array element by its index in MongoDB
To remove an array element by its index in MongoDB, you can use the $unset and $pull operators in a two-step process. The $unset operator sets the array element at the specified index to null, and the $pull operator removes all null values from the array.
Syntax
db.yourCollectionName.update({}, {$unset: {"yourArrayListName.yourPosition": yourPositionValue}});
db.yourCollectionName.update({}, {$pull: {"yourArrayListName": null}});
Sample Data
Let us create a collection with a document to demonstrate the removal process ?
db.removeArrayElements.insertOne({
"StudentName": "Larry",
"StudentAge": 23,
"TechnicalSubject": ["C", "C++", "Java", "MongoDB"]
});
{
"acknowledged" : true,
"insertedId" : ObjectId("5c6ea4879c4643706aef56d2")
}
Display the document using the find() method ?
db.removeArrayElements.find().pretty();
{
"_id" : ObjectId("5c6ea4879c4643706aef56d2"),
"StudentName" : "Larry",
"StudentAge" : 23,
"TechnicalSubject" : [
"C",
"C++",
"Java",
"MongoDB"
]
}
Example: Remove Element at Index 3
Let us remove the "MongoDB" element, which is at index 3 (position 4) in the TechnicalSubject array ?
db.removeArrayElements.update({}, {$unset: {"TechnicalSubject.3": 1}});
db.removeArrayElements.update({}, {$pull: {"TechnicalSubject": null}});
WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })
WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })
Verify Result
Let us display the updated document to confirm the element was removed ?
db.removeArrayElements.find().pretty();
{
"_id" : ObjectId("5c6ea4879c4643706aef56d2"),
"StudentName" : "Larry",
"StudentAge" : 23,
"TechnicalSubject" : [
"C",
"C++",
"Java"
]
}
As you can see in the output, the element "MongoDB" at index 3 has been successfully removed from the TechnicalSubject array.
How It Works
-
Step 1:
$unsetsets the element at the specified index to null, creating a gap in the array -
Step 2:
$pullremoves all null values from the array, effectively closing the gap - Array indexing is zero-based, so index 3 refers to the fourth element
Conclusion
Removing array elements by index in MongoDB requires a two-step process using $unset to nullify the element and $pull to remove null values. This approach maintains array structure while successfully removing elements at specific positions.
