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
Selected Reading
Delete data from a collection in MongoDB using multiple conditions?
To delete data from a MongoDB collection using multiple conditions, use deleteOne() or deleteMany() with a query document containing multiple field-value pairs. All conditions must match for the document to be deleted.
Syntax
db.collection.deleteOne({
"field1": "value1",
"field2": "value2"
});
Sample Data
db.deleteDataDemo.insertMany([
{_id: 1, "Name": "Larry"},
{_id: 2, "Name": "Chris"},
{_id: 3, "Name": "Robert"},
{_id: 4, "Name": "David"},
{_id: 5, "Name": "Carol"},
{_id: 6, "Name": "Sam"}
]);
{
"acknowledged": true,
"insertedIds": [1, 2, 3, 4, 5, 6]
}
Display All Documents
db.deleteDataDemo.find().pretty();
{ "_id": 1, "Name": "Larry" }
{ "_id": 2, "Name": "Chris" }
{ "_id": 3, "Name": "Robert" }
{ "_id": 4, "Name": "David" }
{ "_id": 5, "Name": "Carol" }
{ "_id": 6, "Name": "Sam" }
Example: Delete Using Multiple Conditions
Delete the document where both _id is 4 AND Name is "David" ?
db.deleteDataDemo.deleteOne({
"_id": 4,
"Name": "David"
});
{ "acknowledged": true, "deletedCount": 1 }
Verify Deletion
db.deleteDataDemo.find().pretty();
{ "_id": 1, "Name": "Larry" }
{ "_id": 2, "Name": "Chris" }
{ "_id": 3, "Name": "Robert" }
{ "_id": 5, "Name": "Carol" }
{ "_id": 6, "Name": "Sam" }
Key Points
- Multiple conditions in the query document act as AND operations − all must match.
-
deleteOne()removes the first matching document;deleteMany()removes all matches. - Use
remove()for older MongoDB versions, butdeleteOne()/deleteMany()are preferred.
Conclusion
MongoDB allows precise document deletion using multiple conditions in the query object. All specified field-value pairs must match for successful deletion, providing fine-grained control over data removal operations.
Advertisements
