Section 3: Connection

πŸ”Œ MongoDB Connection Guide

Complete guide to connecting to Local MongoDB and Cloud (Atlas) with connection strings and examples

2 Connection Types
10+ Languages Supported
SSL/TLS Secure Connections
1min Quick Setup
πŸ“–

Connection Overview

Local vs Cloud

πŸ’»
Local MongoDB
MongoDB running on your own machine or server
  • Full control over configuration
  • No internet required after setup
  • Great for development and testing
  • You manage backups and maintenance
  • Default: localhost:27017
☁️
MongoDB Atlas (Cloud)
Fully-managed cloud database service by MongoDB
  • Automatic backups and scaling
  • High availability out-of-the-box
  • Free tier available (512 MB)
  • Global cloud deployment
  • Built-in security and monitoring
πŸ’‘ Which Should You Use?
  • Local: Development, learning, testing, full control needed
  • Atlas: Production apps, need scalability, want managed service
  • Both: Local for dev, Atlas for production (common setup!)
πŸ’»

Connecting to Local MongoDB

Using mongosh and drivers

1
Start MongoDB Server

Make sure MongoDB is running on your machine:

Terminal
# macOS (Homebrew) $ brew services start mongodb-community # Linux (systemd) $ sudo systemctl start mongod # Windows (Manual) C:\> mongod # Verify it's running $ mongosh --eval "db.version()"
7.0.5
2
Connect Using mongosh

The default local connection string:

Local Connection String
mongodb://localhost:27017
Connect to Local MongoDB
# Simple connection (uses localhost:27017 by default) $ mongosh
Connecting to: mongodb://127.0.0.1:27017 Using MongoDB: 7.0.5 Using Mongosh: 2.1.1 test>
# Connect to specific database $ mongosh "mongodb://localhost:27017/myapp" # Connect with custom port $ mongosh "mongodb://localhost:27018"
βœ… Connected! You're now connected to your local MongoDB. Try: show dbs
3
Connect with Authentication (Optional)

If you've enabled authentication:

Authenticated Connection String
mongodb://username:password@localhost:27017/admin
With Credentials
$ mongosh "mongodb://myuser:mypassword@localhost:27017/admin" # OR use --username and --password flags $ mongosh --username myuser --password mypassword --authenticationDatabase admin
☁️

MongoDB Atlas Setup

Cloud database in minutes

1
Create Free Atlas Account
  1. Visit MongoDB Atlas
  2. Sign up with email or Google/GitHub
  3. Verify your email address
  4. Complete the welcome survey (optional)
2
Create a Free Cluster
  1. Click "Build a Database"
  2. Choose "M0 Free" tier (512 MB storage)
  3. Select your cloud provider (AWS, Google Cloud, or Azure)
  4. Choose the region closest to you
  5. Name your cluster (e.g., "Cluster0")
  6. Click "Create" (takes 1-3 minutes)
πŸ’‘ Free Tier Includes:
  • 512 MB storage
  • Shared RAM
  • No credit card required
  • Perfect for learning and small projects
3
Set Up Security

A. Create Database User:

  1. Go to Database Access in left menu
  2. Click "Add New Database User"
  3. Choose Password authentication
  4. Create username and strong password
  5. Set privileges to "Read and write to any database"
  6. Click "Add User"

B. Whitelist IP Address:

  1. Go to Network Access in left menu
  2. Click "Add IP Address"
  3. For development: Click "Allow Access from Anywhere" (0.0.0.0/0)
  4. For production: Add your specific IP
  5. Click "Confirm"
⚠️ Security Best Practice

For production apps, only whitelist specific IPs. "Allow from Anywhere" (0.0.0.0/0) should only be used for development/testing.

4
Get Your Connection String
  1. Go to your Database page
  2. Click "Connect" button on your cluster
  3. Choose "Connect with MongoDB Shell" or "Connect your application"
  4. Copy the connection string
  5. Replace <password> with your actual password
Atlas Connection String Format
mongodb+srv://username:password@cluster0.xxxxx.mongodb.net/myDatabase?retryWrites=true&w=majority
πŸ’‘ Notice the Differences
  • mongodb+srv:// instead of mongodb:// (SRV record)
  • Cluster domain: cluster0.xxxxx.mongodb.net
  • Includes authentication and options
  • Automatic SSL/TLS encryption
5
Connect to Atlas
Connect to MongoDB Atlas
# Replace with your actual connection string $ mongosh "mongodb+srv://myuser:mypassword@cluster0.xxxxx.mongodb.net/"
Current Mongosh Log ID: 657b3a4c9e8a7b2c3d4e5f6a Connecting to: mongodb+srv://cluster0.xxxxx.mongodb.net/ Using MongoDB: 7.0.5 Using Mongosh: 2.1.1 Atlas atlas-xxxxx-shard-0 [primary]>
# Test the connection Atlas> db.version()
7.0.5
# Create a test document Atlas> db.test.insertOne({ message: "Hello from Atlas!" })
βœ… Connected to Cloud! You're now using MongoDB Atlas. Your data is stored in the cloud and accessible from anywhere!
πŸ”—

Connection String Anatomy

Understanding the format

Standard Format
MongoDB Connection String Structure
mongodb://[username:password@]host[:port][/database][?options]
Component Description Example
mongodb:// Protocol (standard) mongodb://
mongodb+srv:// Protocol (DNS SRV - Atlas) mongodb+srv://
username Database user (optional) myuser
password User password (optional) secret123
host Server hostname or IP localhost or cluster0.mongodb.net
port Port number (optional, default: 27017) 27017
database Default database (optional) myapp
options Query parameters (optional) retryWrites=true&w=majority
Common Examples
1. Local without auth
mongodb://localhost:27017
2. Local with auth
mongodb://admin:password123@localhost:27017/admin
3. Remote server
mongodb://192.168.1.100:27017/production
4. Atlas (Cloud)
mongodb+srv://user:pass@cluster0.mongodb.net/mydb
5. With SSL/TLS options
mongodb://host:27017/db?ssl=true&replicaSet=myReplicaSet
πŸ’»

Connect from Code

Popular programming languages

Node.js
Node.js Connection
// Install driver: npm install mongodb const { MongoClient } = require('mongodb'); // Local connection const uri = "mongodb://localhost:27017"; // Atlas connection // const uri = "mongodb+srv://user:pass@cluster0.mongodb.net/"; const client = new MongoClient(uri); async function connect() { try { await client.connect(); console.log("Connected to MongoDB!"); const db = client.db("myapp"); const users = db.collection("users"); // Insert a document await users.insertOne({ name: "Alice", age: 30 }); } finally { await client.close(); } } connect().catch(console.error);
Python
Python Connection
# Install driver: pip install pymongo from pymongo import MongoClient # Local connection uri = "mongodb://localhost:27017" # Atlas connection # uri = "mongodb+srv://user:pass@cluster0.mongodb.net/" client = MongoClient(uri) # Access database and collection db = client.myapp users = db.users # Insert a document result = users.insert_one({"name": "Bob", "age": 25}) print(f"Inserted ID: {result.inserted_id}") # Find documents for user in users.find(): print(user) client.close()
Java
Java Connection
// Add dependency: org.mongodb:mongodb-driver-sync:4.11.0 import com.mongodb.client.MongoClient; import com.mongodb.client.MongoClients; import com.mongodb.client.MongoDatabase; import org.bson.Document; public class MongoDBConnection { public static void main(String[] args) { // Local connection String uri = "mongodb://localhost:27017"; // Atlas connection // String uri = "mongodb+srv://user:pass@cluster0.mongodb.net/"; try (MongoClient client = MongoClients.create(uri)) { MongoDatabase db = client.getDatabase("myapp"); // Insert a document Document doc = new Document("name", "Charlie") .append("age", 35); db.getCollection("users").insertOne(doc); System.out.println("Connected to MongoDB!"); } } }
πŸ”§

Troubleshooting

Common connection issues

Cannot Connect to Local MongoDB

Error: MongoServerError: connect ECONNREFUSED 127.0.0.1:27017

Solutions:

  1. Make sure MongoDB server is running
  2. Check if port 27017 is in use: lsof -i :27017
  3. Verify MongoDB status:
    • macOS: brew services list
    • Linux: sudo systemctl status mongod
    • Windows: Check Services or Task Manager
  4. Check firewall settings
Authentication Failed

Error: MongoServerError: Authentication failed

Solutions:

  1. Verify username and password are correct
  2. Check you're connecting to the right authentication database (usually admin)
  3. For Atlas: Make sure you replaced <password> in connection string
  4. Special characters in password? URL encode them:
    • @ becomes %40
    • : becomes %3A
    • / becomes %2F
Cannot Connect to Atlas

Error: MongoServerSelectionError: connection timeout

Solutions:

  1. IP Whitelist: Make sure your IP is whitelisted in Atlas Network Access
  2. Firewall: Check your local firewall isn't blocking port 27017
  3. VPN: Some VPNs block MongoDB connections - try without VPN
  4. Connection String: Verify you're using mongodb+srv:// (not mongodb://)
  5. Cluster Running: Ensure your Atlas cluster is active (not paused)
SSL/TLS Certificate Error

Error: unable to verify the first certificate

Solution:

Add SSL options to connection string:

mongodb://host:27017/db?ssl=true&sslValidate=false
⚠️ Security Warning Only use sslValidate=false in development. In production, use proper SSL certificates.