Getting Started (Takes 2 minutes)
First things first - let's get MongoDB installed in your project:
# Just run this in your terminal
npm install mongodb
That's it! You're ready to go.
Connecting to Your Database
Here's how I usually set up my MongoDB connection. Pretty straightforward:
const { MongoClient } = require('mongodb');
// Your database URL - change this to match your setup
const uri = 'mongodb://localhost:27017';
const client = new MongoClient(uri);
async function connectToDatabase() {
try {
await client.connect();
console.log('Hey, we\'re connected!');
const db = client.db('myapp');
const users = db.collection('users');
// Do your stuff here
} catch (error) {
console.log('Oops, connection failed:', error);
} finally {
await client.close();
}
}
The Big Four: Create, Read, Update, Delete
Adding New Data (Create)
// Adding one user
const newUser = await users.insertOne({
name: 'Sarah',
email: 'sarah@example.com',
age: 28
});
console.log('New user added! ID:', newUser.insertedId);
// Adding multiple users at once - super handy
const manyUsers = await users.insertMany([
{ name: 'Mike', email: 'mike@example.com', age: 32 },
{ name: 'Emma', email: 'emma@example.com', age: 26 }
]);
console.log(`Added ${manyUsers.insertedCount} users`);
Getting Your Data Back (Read)
// Get everyone
const everyone = await users.find({}).toArray();
// Find just one person
const person = await users.findOne({ name: 'Sarah' });
// Find people over 18 (because why not)
const adults = await users.find({ age: { $gte: 18 } }).toArray();
// Get the top 5 oldest users, sorted
const oldestUsers = await users
.find({})
.sort({ age: -1 })
.limit(5)
.toArray();
// Sometimes you don't need everything - just grab names and emails
const contacts = await users
.find({}, { projection: { name: 1, email: 1, _id: 0 } })
.toArray();
Updating Existing Data
// Change one person's age
const updated = await users.updateOne(
{ name: 'Sarah' },
{ $set: { age: 29 } }
);
console.log(`Updated ${updated.modifiedCount} person`);
// Update everyone under 18 (set them as minors)
await users.updateMany(
{ age: { $lt: 18 } },
{ $set: { status: 'minor' } }
);
// Replace someone's entire record (keeping the same ID)
await users.replaceOne(
{ name: 'Sarah' },
{
name: 'Sarah Johnson',
email: 'sarah.johnson@example.com',
age: 29,
city: 'Boston'
}
);
Removing Data (Delete)
// Remove one person
const removed = await users.deleteOne({ name: 'Sarah' });
console.log(`Removed ${removed.deletedCount} person`);
// Remove all minors (careful with this one!)
await users.deleteMany({ age: { $lt: 18 } });
Some Useful Query Tricks
// Find people named John OR Jane
const result = await users.find({
$or: [
{ name: 'John' },
{ name: 'Jane' }
]
}).toArray();
// Count how many adults you have
const adultCount = await users.countDocuments({ age: { $gte: 18 } });
// Check if someone exists (returns true/false)
const userExists = await users.findOne({ email: 'sarah@example.com' }) !== null;
// Get all unique ages in your database
const uniqueAges = await users.distinct('age');
A Complete Working Example
This is what I typically use as a starting point:
const { MongoClient } = require('mongodb');
async function runExample() {
const uri = 'mongodb://localhost:27017';
const client = new MongoClient(uri);
try {
// Connect
await client.connect();
console.log('Connected successfully!');
const db = client.db('myapp');
const users = db.collection('users');
// Add a new user
const newUser = await users.insertOne({
name: 'Alex Smith',
email: 'alex@example.com',
age: 25,
createdAt: new Date()
});
console.log('Created user:', newUser.insertedId);
// Find all adults
const adults = await users.find({ age: { $gte: 18 } }).toArray();
console.log(`Found ${adults.length} adults`);
// Update Alex's age
const updateResult = await users.updateOne(
{ email: 'alex@example.com' },
{ $set: { age: 26 } }
);
console.log('Updated Alex\'s age');
// Clean up - remove Alex
const deleteResult = await users.deleteOne({ email: 'alex@example.com' });
console.log('Removed Alex from database');
} catch (error) {
console.log('Something went wrong:', error);
} finally {
await client.close();
console.log('Connection closed');
}
}
runExample();
MongoDB Query Cheat Sheet
These are the operators I use most often:
// Basic comparisons
{ age: { $gt: 18 } } // older than 18
{ age: { $gte: 18 } } // 18 or older
{ age: { $lt: 65 } } // younger than 65
{ age: { $ne: 30 } } // not 30 years old
{ age: { $in: [25, 30, 35] } } // age is 25, 30, or 35
// Text searches
{ name: { $regex: 'sarah', $options: 'i' } } // case-insensitive
{ email: { $exists: true } } // has email field
// Combining conditions
{ $and: [{ age: { $gte: 18 } }, { age: { $lt: 65 } }] } // between 18-65
{ $or: [{ name: 'John' }, { name: 'Jane' }] } // John OR Jane
Working with Arrays and Updates
// Update operators I use regularly
{ $set: { age: 30 } } // set a value
{ $inc: { age: 1 } } // add 1 to age
{ $unset: { oldField: '' } } // remove a field
{ $push: { hobbies: 'reading' } } // add to array
{ $pull: { hobbies: 'gaming' } } // remove from array
{ $currentDate: { lastSeen: true } } // set current timestamp
Better Connection Management
Here's a cleaner way to handle database connections:
class Database {
constructor(uri = 'mongodb://localhost:27017', dbName = 'myapp') {
this.client = new MongoClient(uri);
this.dbName = dbName;
this.db = null;
}
async connect() {
await this.client.connect();
this.db = this.client.db(this.dbName);
console.log('Database connected');
return this.db;
}
async disconnect() {
await this.client.close();
console.log('Database disconnected');
}
collection(name) {
return this.db.collection(name);
}
}
// Use it like this:
const database = new Database();
await database.connect();
const users = database.collection('users');
// do your operations...
await database.disconnect();
Things to Remember
- Always use
await
with database operations (they're asynchronous) - Don't forget
.toArray()
when usingfind()
- it returns a cursor, not an array - Close your connections when you're done -
client.close()
- Handle errors properly with try-catch blocks
- When querying large datasets, consider using projections to only get the fields you need
That covers pretty much everything you'll need for day-to-day MongoDB work with Node.js. Start with the basics and build from there - you'll be surprised how much you can accomplish with just these operations!
Top comments (0)