MongoDB Delete Statement
Open MongoDB Shell
- Open the MongoDB Shell from Linux shell
- Switch to our "employee" database
# mongosh
Current Mongosh Log ID: 6117225c105379b62b6abaa9
Connecting to: mongodb://127.0.0.1:27017/?directConnection=true&serverSelectionTimeoutMS=2000
Using MongoDB: 5.0.2
Using Mongosh: 1.0.5
For mongosh info see: https://docs.mongodb.com/mongodb-shell/
test>
# use employee
switched to db employee
Delete Single Record
- Run following command to delete one record from "emp_info" collection
employee> db.emp_info.deleteOne( { first:"Allan" } )
{ acknowledged: true, deletedCount: 1 }
Show the current records in collections. The record with "first" name "Allan" is no longer in collection.
employee> db.emp_info.find()
[
{
_id: ObjectId("61172935a1766234eab5b87a"),
first: 'John',
last: 'Davis',
role: 'Dev',
country: 'United States of America'
},
{
_id: ObjectId("61172c1ca1766234eab5b87f"),
first: 'Sam',
last: 'Doe',
role: 'Senior Manager',
country: 'United States of America'
}
]
Delete Multiple Records
- Run following command to delete multiple record from "emp_info" collection
employee> db.emp_info.deleteMany( { country:"United States of America" } )
{ acknowledged: true, deletedCount: 2 }
Show the current records in collections. All record are deleted and are no longer in collection.
employee> db.emp_info.find()