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 need | Version / notes |
|---|---|
| Docker (recommended) | Docker Desktop or Docker Engine to run the database locally – see the Docker guide |
| Or MongoDB Community Server | Native install for Windows/macOS/Linux |
| mongosh + Compass | Command-line shell and GUI |
| Node.js LTS | For the sample app |
3. Local setup
1Run MongoDB with Docker
Fastest way – data persists in the
mongo-datavolume.BASHdocker run -d --name mongo -p 27017:27017 -v mongo-data:/data/db mongo:82Or 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 themongodservice.3Connect with mongosh or Compass
Install mongosh and MongoDB Compass (GUI). The default local URI is
mongodb://localhost:27017.BASHmongosh "mongodb://localhost:27017" show dbs
4. Create & run a project
1Basic CRUD in mongosh
Databases and collections are created on first insert.
JSuse 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 })2Create a Node.js app with Mongoose
Mongoose adds schemas, validation and models on top of the driver.
BASHmkdir mongo-app && cd mongo-app npm init -y && npm pkg set type=module npm install mongoose3Define a model and query it
Connect once at startup and reuse the connection.
index.jsimport 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();4Run it
You should see the matching products printed.
BASHnode --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.
# local
MONGODB_URI=mongodb://localhost:27017/shop
# Atlas (production)
# MONGODB_URI=mongodb+srv://appUser:PASSWORD@cluster0.xxxxx.mongodb.net/shop?retryWrites=true&w=majorityKey dependencies
| Package / tool | Used for |
|---|---|
mongodb | Official Node.js driver |
mongoose | ODM: schemas, validation, middleware |
mongosh | Shell |
MongoDB Compass | GUI for browsing and indexes |
mongodump / mongorestore | Backup and restore (Database Tools) |
Folder structure
mongo-app/
├── src/
│ ├── db.js # mongoose.connect once
│ ├── models/
│ │ └── Product.js
│ └── routes/
├── .env
└── package.jsonEssential commands
| Command | What it does |
|---|---|
mongosh "<uri>" | Open a shell |
show dbs / show collections | List 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
| Requirement | Recommendation |
|---|---|
| Recommended | MongoDB Atlas cluster in the same cloud region as your app |
| Self-hosted | 3-node replica set on VPSes with SSD, auth enabled, private network |
| Security | Database users with least privilege, IP allow-list / VPC peering, TLS |
| Backups | Atlas continuous backups or scheduled mongodump + off-site copies |
Deployment steps
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.
2Create a database user
In Database Access add a user with a strong password and a role limited to your database (e.g.
readWriteonshop).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.4Copy the connection string to the server
Use Connect → Drivers to copy the
mongodb+srv://URI and store it in the app’s environment.OUTPUTMONGODB_URI=mongodb+srv://appUser:PASSWORD@cluster0.xxxxx.mongodb.net/shop?retryWrites=true&w=majority5Self-hosted alternative: enable authentication
If you run
mongodyourself, create an admin user, turn on authorization and keep it on a private interface, then restart withsudo systemctl restart mongod./etc/mongod.confnet: port: 27017 bindIp: 127.0.0.1,10.0.0.5 # private IPs only security: authorization: enabled6Back up regularly
For self-hosted servers schedule
mongodumpand copy the archive off the server (e.g. to S3).BASHmongodump --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.
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.