How to use MongoDB Shell

how to use MongoDB Shell (mongosh) at the command terminal:

1. Start MongoDB Shell

If MongoDB is running, open your terminal or command prompt and type:

mongosh

This connects to the local MongoDB instance (mongodb://localhost:27017 by default).


2. Check the MongoDB Version

After launching mongosh, you can verify the version:

db.version()

3. Show Available Databases

To list all databases:

show dbs

4. Create or Switch to a Database

To create or switch to a database (testDB in this case):

use testDB

5. Create a Collection and Insert Documents

Collections in MongoDB are equivalent to tables in SQL.

Insert a Single Document

Insert Multiple Documents


6. Retrieve Data

Find All Documents

Find a Specific Document

Find Documents with Filtering


7. Update Documents

Update a Single Document

Update Multiple Documents


8. Delete Documents

Delete One Document

Delete Multiple Documents


9. Drop a Collection

To delete the users collection:


10. Exit MongoDB Shell

To exit mongosh:


Final Output Example

After executing db.users.find().pretty(), you might see:


This example covers the basic CRUD (Create, Read, Update, Delete) operations in MongoDB Shell (mongosh). 🚀

Last updated