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:
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:
3. Show Available Databases
To list all databases:
4. Create or Switch to a Database
To create or switch to a database (testDB
in this case):
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