0
0
MongoDBquery~5 mins

MongoDB Shell (mongosh) basics

Choose your learning style9 modes available
Introduction

The MongoDB Shell (mongosh) lets you talk to your database using simple commands. It helps you see, add, or change data easily.

You want to quickly check what data is in your database.
You need to add new information to your database by typing commands.
You want to update or fix some data without using a complex program.
You are learning how MongoDB works by trying commands step-by-step.
You want to delete old or wrong data from your database.
Syntax
MongoDB
mongosh

// Show databases
show dbs

// Switch to a database
use databaseName

// Show collections (tables)
show collections

// Find documents in a collection
db.collectionName.find()

// Insert a document
db.collectionName.insertOne({key: "value"})

mongosh is the command to start the MongoDB shell.

Commands like show dbs and use help you navigate databases.

Examples
Lists all databases on the server.
MongoDB
show dbs
Switches to the database named 'myDatabase'.
MongoDB
use myDatabase
Shows all collections (like tables) in the current database.
MongoDB
show collections
Displays all documents (records) in the 'users' collection.
MongoDB
db.users.find()
Sample Program

This example connects to MongoDB, switches to 'testDB', shows collections, adds a product, and then shows all products.

MongoDB
mongosh

show dbs
use testDB
show collections
db.products.insertOne({name: "Pen", price: 1.5})
db.products.find()
OutputSuccess
Important Notes

Commands are case-sensitive; type them exactly as shown.

Use db.collectionName.find().pretty() to see results in a readable format.

Remember to switch to the right database before running commands.

Summary

mongosh is your tool to interact with MongoDB using commands.

Use show dbs, use, and show collections to explore your data.

Insert and find data easily with insertOne() and find().