Databases & Caching

MongoDB Setup & Deployment Guide

Document database for JSON-like data – run it locally, use it from Node.js with the driver or Mongoose, and go live on Atlas or your own server.

Updated Official documentation ↗

1. Introduction & use cases

MongoDB stores data as documents (BSON, a binary form of JSON) in collections. Documents in one collection can have different fields, nested objects and arrays, so the data model can follow your application objects closely.

It supports rich queries, secondary indexes, aggregation pipelines, multi-document transactions on replica sets, full-text search (on Atlas) and horizontal scaling with sharding. MongoDB Atlas is the official managed cloud service, with a free tier for learning.

Where it is used

  • Content management, catalogues and user profiles
  • Mobile and web app back-ends with evolving schemas
  • Event logging and analytics
  • Real-time apps together with change streams

2. Prerequisites

You needVersion / notes
Docker (recommended)Docker Desktop or Docker Engine to run the database locally – see the Docker guide
Or MongoDB Community ServerNative install for Windows/macOS/Linux
mongosh + CompassCommand-line shell and GUI
Node.js LTSFor the sample app

3. Local setup

  1. 1Run MongoDB with Docker

    Fastest way – data persists in the mongo-data volume.

    BASH
    docker run -d --name mongo -p 27017:27017 -v mongo-data:/data/db mongo:8
  2. 2Or install natively

    Download MongoDB Community Server for your OS from mongodb.com (Windows MSI, macOS via Homebrew mongodb-community, Linux via the official apt/yum repository) and start the mongod service.

  3. 3Connect with mongosh or Compass

    Install mongosh and MongoDB Compass (GUI). The default local URI is mongodb://localhost:27017.

    BASH
    mongosh "mongodb://localhost:27017"
    show dbs

4. Create & run a project

  1. 1Basic CRUD in mongosh

    Databases and collections are created on first insert.

    JS
    use shop
    db.products.insertMany([
      { name: 'Pen', price: 25, tags: ['stationery'] },
      { name: 'Notebook', price: 80, tags: ['stationery', 'paper'] }
    ])
    db.products.find({ price: { $lt: 50 } })
    db.products.updateOne({ name: 'Pen' }, { $set: { price: 30 } })
    db.products.deleteOne({ name: 'Notebook' })
    db.products.createIndex({ name: 1 }, { unique: true })
  2. 2Create a Node.js app with Mongoose

    Mongoose adds schemas, validation and models on top of the driver.

    BASH
    mkdir mongo-app && cd mongo-app
    npm init -y && npm pkg set type=module
    npm install mongoose
  3. 3Define a model and query it

    Connect once at startup and reuse the connection.

    index.js
    import mongoose from 'mongoose';
    
    await mongoose.connect(process.env.MONGODB_URI ?? 'mongodb://localhost:27017/shop');
    
    const Product = mongoose.model('Product', new mongoose.Schema({
      name: { type: String, required: true, unique: true },
      price: { type: Number, min: 0 },
      tags: [String],
    }, { timestamps: true }));
    
    await Product.create({ name: 'Marker', price: 40, tags: ['stationery'] });
    const cheap = await Product.find({ price: { $lt: 50 } }).lean();
    console.log(cheap);
    await mongoose.disconnect();
  4. 4Run it

    You should see the matching products printed.

    BASH
    node --env-file=.env index.js

✅ When it works you should see output like Figure 1.

5. Development configuration

Environment variables

The connection string includes the database name and, in production, credentials and options. Atlas uses the mongodb+srv:// format.

.env
# local
MONGODB_URI=mongodb://localhost:27017/shop

# Atlas (production)
# MONGODB_URI=mongodb+srv://appUser:PASSWORD@cluster0.xxxxx.mongodb.net/shop?retryWrites=true&w=majority

Key dependencies

Package / toolUsed for
mongodbOfficial Node.js driver
mongooseODM: schemas, validation, middleware
mongoshShell
MongoDB CompassGUI for browsing and indexes
mongodump / mongorestoreBackup and restore (Database Tools)

Folder structure

project structure
mongo-app/
├── src/
│   ├── db.js          # mongoose.connect once
│   ├── models/
│   │   └── Product.js
│   └── routes/
├── .env
└── package.json

Essential commands

CommandWhat it does
mongosh "<uri>"Open a shell
show dbs / show collectionsList databases and collections
db.coll.find().explain("executionStats")Check if a query uses an index
mongodump --uri "<uri>" --out backup/Back up a database
mongorestore --uri "<uri>" backup/Restore a backup

6. Production deployment

Server & hosting requirements

RequirementRecommendation
RecommendedMongoDB Atlas cluster in the same cloud region as your app
Self-hosted3-node replica set on VPSes with SSD, auth enabled, private network
SecurityDatabase users with least privilege, IP allow-list / VPC peering, TLS
BackupsAtlas continuous backups or scheduled mongodump + off-site copies

Deployment steps

  1. 1Create an Atlas cluster

    Sign in to MongoDB Atlas, create a project and a cluster (free/flex tier for testing, dedicated tier for production), and pick the provider and region closest to your servers.

  2. 2Create a database user

    In Database Access add a user with a strong password and a role limited to your database (e.g. readWrite on shop).

  3. 3Allow your servers’ IPs

    In Network Access add the public IPs of your app servers (avoid 0.0.0.0/0). On AWS/GCP/Azure use VPC peering or Private Endpoint for a private connection.

  4. 4Copy the connection string to the server

    Use Connect → Drivers to copy the mongodb+srv:// URI and store it in the app’s environment.

    OUTPUT
    MONGODB_URI=mongodb+srv://appUser:PASSWORD@cluster0.xxxxx.mongodb.net/shop?retryWrites=true&w=majority
  5. 5Self-hosted alternative: enable authentication

    If you run mongod yourself, create an admin user, turn on authorization and keep it on a private interface, then restart with sudo systemctl restart mongod.

    /etc/mongod.conf
    net:
      port: 27017
      bindIp: 127.0.0.1,10.0.0.5   # private IPs only
    security:
      authorization: enabled
  6. 6Back up regularly

    For self-hosted servers schedule mongodump and copy the archive off the server (e.g. to S3).

    BASH
    mongodump --uri "$MONGODB_URI" --archive=/backups/shop-$(date +%F).gz --gzip

🗺 The whole path from your code to the live site is drawn in the deployment diagram.

7. Images & screenshots

Illustrations drawn for this guide from the commands above. Product dashboards change often, so for screens such as cloud consoles follow the step text and the official documentation.

terminal$ node --env-file=.env index.js[ { _id: new ObjectId('6750a1f2c9e77b1d2a4f0e11'), name: 'Pen', price: 30, tags: [ 'stationery' ] }, { _id: new ObjectId('6750a2...'), name: 'Marker', price: 40, ... }]
Figure 1: terminal output of the sample MongoDB project (section 4).
1Schema + indexes2Atlas cluster3DB user + IPallow-list4App withmongodb+srv URI5Backups +monitoring
Figure 2: production deployment flow (section 6).
mongo-app/├── src/│ ├── db.js # mongoose.connect once│ ├── models/│ │ └── Product.js│ └── routes/├── .env└── package.json
Figure 3: project folder structure (section 5).

8. Common errors & solutions

MongoServerSelectionError: connect ECONNREFUSED 127.0.0.1:27017

MongoDB is not running locally. Start the container/service (docker start mongo or sudo systemctl start mongod).

Atlas: Could not connect to any servers in your MongoDB Atlas cluster

Your server’s IP is not in Network Access, or the password contains special characters that must be URL-encoded.

E11000 duplicate key error

A unique index rejected a duplicate value. Handle it as a validation error in your app.

Slow queries / high CPU

Run explain("executionStats"); if it shows COLLSCAN, add an index matching the filter and sort.

MongoServerError: Authentication failed

Wrong user, password or authSource. Users created in admin need ?authSource=admin in the URI.

Best practices

  • Embed data that is read together; reference data that grows without limit.
  • Create indexes for every frequent query and review them as features change.
  • Use one MongoClient/Mongoose connection per process (connection pooling).
  • Validate data (Mongoose schemas or JSON Schema validation).
  • Never expose port 27017 publicly; always enable auth and TLS.