MongoDB Shell
Welcome to mongosh โ your command-line best friend for working with MongoDB. Think of it as a powerful calculator that speaks MongoDB. It's where you'll write queries, insert data, and manage your databases.
If you've ever used a terminal or command prompt, you'll feel right at home. mongosh is interactive, meaning you type commands and see results immediately. It's like having a conversation with your database!
Basic Commands
Let's learn some essential commands. First, show dbs lists all your databases. It's like looking at your file explorer and seeing all your folders.
The use command switches to a database. Don't worry if it doesn't exist yet โ MongoDB creates it when you first store data. show collections shows you the collections in your current database, like listing files in a folder.
show dbs
use school
show collections
Running Queries
Now let's actually do something useful! You can find documents using find() and insert new ones with insertOne() or insertMany(). These are the bread and butter of MongoDB operations.
Think of find() as asking your database a question: "Hey, give me all the documents that match this criteria." You can make your questions as simple or complex as you need.
db.students.insertMany([
{ name: "Alice", grade: "A", age: 20 },
{ name: "Bob", grade: "B", age: 22 },
{ name: "Charlie", grade: "A", age: 21 }
])
db.students.find({ grade: "A" })
Try it Yourself โ
Help Commands
Stuck or curious? Just type help to see a list of available commands. You can also type db.help() to see all the methods available on the database object. It's like having a built-in cheat sheet!
Don't be afraid to explore โ you can't break anything by just looking at help. Practice makes perfect, so experiment freely.
help
db.help()
db.collection.help()