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/myFirstDatabase

Working with Databases

In MongoDB, databases hold collections of documents.

1. Show All Databases

show dbs

2. 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_db

3. Check Current Database

db

4. Drop Database

db.dropDatabase()

Working with Collections

Collections are similar to tables in RDBMS.

1. Show Collections

show collections

2. 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.