MongoDB Basics
What is MongoDB?
MongoDB is a document-oriented database built for flexibility and speed. Rather than storing data in rigid rows and columns, MongoDB stores each record as a document — a JSON-like structure called BSON (Binary JSON). BSON is simply JSON with added data types like Date and ObjectId.
MongoDB was created in 2009 and is now one of the most popular databases in the world. It powers applications at companies like Uber, Forbes, and eBay.
Core Concepts
Documents
A MongoDB document is a JSON object. Every document has a unique identifier called _id — MongoDB generates this automatically if you do not provide one.
{
"_id": "64f2a3b1c8e4a12345678901",
"name": "Ngozi Okonkwo",
"email": "ngozi@example.com",
"age": 27,
"skills": ["Node.js", "MongoDB", "Express"],
"address": {
"city": "Abuja",
"country": "Nigeria"
},
"createdAt": "2024-09-01T08:00:00Z"
}
Notice that a document can hold nested objects (address) and arrays (skills) — this would require multiple tables in SQL.
Collections vs Tables
In SQL you have tables. In MongoDB you have collections. A collection is a group of related documents, like a folder of files.
| SQL concept | MongoDB equivalent |
|---|---|
| Database | Database |
| Table | Collection |
| Row | Document |
| Column | Field |
| Primary key | _id |
Installing MongoDB and Mongoose
In your Node.js project, you will almost always use Mongoose — a library that sits on top of the MongoDB driver and makes working with your database much easier (more on Mongoose in the next lesson). For now, let's set up the connection.
npm install mongoose
You will also need a MongoDB database. The easiest option is MongoDB Atlas — a free cloud-hosted MongoDB service at mongodb.com/atlas. Create a free cluster and copy your connection string.
Connecting to MongoDB
// db.js
const mongoose = require('mongoose');
const connectDB = async () => {
try {
await mongoose.connect(process.env.MONGO_URI);
console.log('MongoDB connected successfully');
} catch (error) {
console.error('MongoDB connection failed:', error.message);
process.exit(1); // Exit the process if connection fails
}
};
module.exports = connectDB;
Call this function when your server starts:
// server.js
require('dotenv').config();
const express = require('express');
const connectDB = require('./db');
const app = express();
app.use(express.json());
connectDB();
app.listen(3000, () => console.log('Server running on port 3000'));
Your .env file:
MONGO_URI=mongodb+srv://youruser:yourpassword@cluster0.mongodb.net/myapp
Basic MongoDB Queries
Once connected, you interact with MongoDB through collections. Below are the five fundamental operations you will use in almost every project.
findOne — Retrieve a single document
const User = require('./models/User'); // Mongoose model
// Find a user by email
const user = await User.findOne({ email: 'ngozi@example.com' });
console.log(user); // The full document, or null if not found
find — Retrieve multiple documents
// Find all users from Abuja
const users = await User.find({ 'address.city': 'Abuja' });
console.log(users); // An array of matching documents
insertOne (Mongoose: save or create) — Create a new document
// Create and save a new user
const newUser = new User({
name: 'Emeka',
email: 'emeka@example.com',
age: 30,
});
await newUser.save();
// Or use the shorter create() method
const anotherUser = await User.create({
name: 'Fatima',
email: 'fatima@example.com',
age: 24,
});
updateOne — Update a document
// Update Emeka's age
await User.updateOne(
{ email: 'emeka@example.com' }, // filter: which document to update
{ $set: { age: 31 } } // update: what to change
);
The $set operator tells MongoDB to update only the specified fields. Without $set, MongoDB would replace the entire document with just { age: 31 }.
deleteOne — Delete a document
// Delete a user by email
await User.deleteOne({ email: 'emeka@example.com' });
Putting It Together in an Express Route
Here is how you would use these queries inside real API routes:
const express = require('express');
const router = express.Router();
const User = require('../models/User');
// GET /users — get all users
router.get('/', async (req, res) => {
try {
const users = await User.find();
res.json(users);
} catch (error) {
res.status(500).json({ error: error.message });
}
});
// GET /users/:id — get one user
router.get('/:id', async (req, res) => {
try {
const user = await User.findById(req.params.id);
if (!user) return res.status(404).json({ message: 'User not found' });
res.json(user);
} catch (error) {
res.status(500).json({ error: error.message });
}
});
// POST /users — create a new user
router.post('/', async (req, res) => {
try {
const user = await User.create(req.body);
res.status(201).json(user);
} catch (error) {
res.status(400).json({ error: error.message });
}
});
// DELETE /users/:id — delete a user
router.delete('/:id', async (req, res) => {
try {
await User.findByIdAndDelete(req.params.id);
res.json({ message: 'User deleted' });
} catch (error) {
res.status(500).json({ error: error.message });
}
});
module.exports = router;
Practice Exercise
Build a simple contact book API using MongoDB:
- Set up a free MongoDB Atlas cluster and get your connection string
- Create a
Contactmodel with fields:name,phone,email,group(e.g. "work" or "family") - Add four routes:
GET /contacts,GET /contacts/:id,POST /contacts,DELETE /contacts/:id - Test your routes using Postman or Thunder Client
- Bonus: Add a
GET /contacts?group=workroute that filters contacts by group using a query parameter
Try it yourself
Key Takeaways
- MongoDB stores data as BSON documents (JSON-like objects) in collections, rather than rows in tables.
- Every MongoDB document has a unique _id field — generated automatically as an ObjectId if not provided.
- The five essential operations are find, findOne, create/save (insert), updateOne with $set, and deleteOne.
- Use Mongoose's connectDB pattern to establish your database connection before starting your Express server.
- Always wrap MongoDB operations in try/catch blocks inside async route handlers to handle errors gracefully.
Quick Quiz
1.What is the equivalent of a SQL 'table' in MongoDB?
2.What does the $set operator do in a MongoDB updateOne() call?
3.What is BSON in the context of MongoDB?
4.What happens if you call User.findById('nonexistent_id') and no document matches?
Ready to go further?
CareerEx gives you structured 12-week training, live classes every Saturday and Sunday, real tutor feedback, and a certificate. Join the next cohort.
Join CareerEx