Geek Slack

MongoDB Tutorial
About Lesson



MongoDB mongosh Delete


MongoDB mongosh Delete

Introduction

Learn how to delete documents from a MongoDB collection using the mongosh shell interface.

Connecting to MongoDB

Before deleting documents, ensure you are connected to your MongoDB server:

Example: Connecting to MongoDB

mongosh

This command starts the mongosh shell and connects to the default MongoDB server running locally.

Switching to a Database

Switch to the database where your collection resides using the use command:

Example: Switching to a Database

use mydatabase

This command switches to the “mydatabase” database. Replace mydatabase with your database name.

Deleting Documents

To delete documents from a MongoDB collection, use the deleteOne or deleteMany methods:

Example: Deleting a Single Document

db.mycollection.deleteOne({ name: "John Doe" })

This command deletes a single document from the mycollection collection where the name field equals “John Doe”.

Example: Deleting Multiple Documents

db.mycollection.deleteMany({ status: "inactive" })

This command deletes multiple documents from the mycollection collection where the status field equals “inactive”.

Deleting All Documents

To delete all documents from a collection, omit the filter criteria:

Example: Deleting All Documents

db.mycollection.deleteMany({})

This command deletes all documents from the mycollection collection.

Verifying Deletions

Verify that the documents have been deleted by querying the collection:

Example: Verifying Deletions

db.mycollection.find()

This command retrieves all remaining documents from the mycollection collection after deletion. Ensure that the expected documents have been removed.

Conclusion

Deleting documents in a MongoDB collection using mongosh provides control over data management operations. Experiment with different delete methods and criteria to suit your application’s requirements.

Join the conversation