delete data

To delete Data in MongoDB document or collections, mongodb use deleteOne, and deleteMany methods.

We will use a sample database (cars ) shown below for reference. The name of collection is suzuki.

Sample Database


[{"name": "swift","type": "hatchback","price":"800000"},
 {"name": "ciaz","type": "sedan","price":"1000000"},
 {"name": "baleno","type": "hatchback","price":"850000"},
 {"name": "scross","type": "crossover","price":"11500000"},
 {"name": "brezza","type": "suv","price":"990000"},
 {"name": "gypsy","type": "suv","price":"750000"}
]    

deleteOne

deleteOne method is used to delete one document that match condition.

{ "acknowledged" : true, "deletedCount" : 1 } 
db.suzuki.deleteOne({name:'gypsy'})

Check after delete

{ "_id" : ObjectId("5eb80ed75a31fe0e056e0d35"), "name" : "swift", "type" : "hatchback", "price" : 800000 }
{ "_id" : ObjectId("5eb80ed75a31fe0e056e0d36"), "name" : "ciaz", "type" : "sedan", "price" : 1000000 }
{ "_id" : ObjectId("5eb80ed75a31fe0e056e0d37"), "name" : "baleno", "type" : "hatchback", "price" : 850000 }
{ "_id" : ObjectId("5eb80ed75a31fe0e056e0d38"), "name" : "scross", "type" : "crossover", "price" : 11500000 }
{ "_id" : ObjectId("5eb80ed75a31fe0e056e0d39"), "name" : "brezza", "type" : "suv", "price" : 990000 }
db.suzuki.find()

deleteMany

deleteMany is used to delete all data in documents.

{ "acknowledged" : true, "deletedCount" : 2 }
db.suzuki.deleteMany({price:{$gt:990000}})

Check after update

{ "_id" : ObjectId("5eb80ed75a31fe0e056e0d35"), "name" : "swift", "type" : "hatchback", "price" : 800000 }
{ "_id" : ObjectId("5eb80ed75a31fe0e056e0d37"), "name" : "baleno", "type" : "hatchback", "price" : 850000 }
{ "_id" : ObjectId("5eb80ed75a31fe0e056e0d39"), "name" : "brezza", "type" : "suv", "price" : 990000 }
db.suzuki.find()