MongoDB Tutorial
- Home
- Introduction
- Installation
- Connection & Databases
- CRUD Operations
- Comparison Operators
- Logical Operators
- Array Operators
- Evaluation Operators
- Update Operators
- Projection & Sorting
- Cursor Methods
- Querying Nested Docs
- Upserts & Indexes
- Aggregation Framework
- Data Modeling
- Validations & Transactions
- Geospatial Queries
- Advanced Indexing
- MongoDB with Next.js
- Best Practices
Connection & Databases
After installation, you interact with MongoDB using the MongoDB Shell (mongosh) or a driver (like Node.js).
The Connection String
MongoDB uses a URI format for connections:
# Local Connection
mongodb://localhost:27017
# Atlas (Cloud) Connection
mongodb+srv://<username>:<password>@cluster.mongodb.net/myFirstDatabaseWorking with Databases
In MongoDB, databases hold collections of documents.
1. Show All Databases
show dbs2. Create or Switch Database
The `use` command is used to switch to a database. If it doesn't exist, MongoDB creates it when you first save data.
use my_new_db3. Check Current Database
db4. Drop Database
db.dropDatabase()Working with Collections
Collections are similar to tables in RDBMS.
1. Show Collections
show collections2. Create Collection (Explicitly)
db.createCollection("users")3. Drop Collection
db.users.drop()Note: In MongoDB, you don't *have* to create a database or collection explicitly. They are created automatically when you insert the first document.