Node.js with MongoDB: Database, Collections, and CRUD
What is MongoDB?
MongoDB is a NoSQL, document-oriented database. Instead of tables and rows, it stores data as flexible JSON-like documents (BSON) grouped into collections inside a database.
| RDBMS Term | MongoDB Equivalent |
|---|---|
| Database | Database |
| Table | Collection |
| Row | Document |
| Column | Field |
Connecting Node.js to MongoDB
npm install mongodb
const { MongoClient } = require('mongodb');
const uri = 'mongodb://localhost:27017';
const client = new MongoClient(uri);
async function main() {
await client.connect();
console.log('Connected to MongoDB');
// Create/select a database
const db = client.db('schoolDB');
// Create/select a collection
const students = db.collection('students');
// ... CRUD operations go here
await client.close();
}
main().catch(console.error);
MongoDB creates the database and collection automatically the first time data is written to them — no explicit CREATE DATABASE step is required.
Insert
// Insert one document
await students.insertOne({ name: 'Alice', age: 20, course: 'CSE' });
// Insert many documents
await students.insertMany([
{ name: 'Bob', age: 22, course: 'IT' },
{ name: 'Carol', age: 21, course: 'CSE' }
]);
Query (Find)
// Find all documents
const all = await students.find({}).toArray();
// Find with a filter
const cseStudents = await students.find({ course: 'CSE' }).toArray();
// Find one document
const alice = await students.findOne({ name: 'Alice' });
// Query operators
const adults = await students.find({ age: { $gte: 18 } }).toArray();
Common Query Operators
| Operator | Meaning |
|---|---|
$eq | Equal to |
$gt / $gte | Greater than / or equal |
$lt / $lte | Less than / or equal |
$in | Value in a list |
$and / $or | Logical AND / OR |
Update
// Update one document
await students.updateOne(
{ name: 'Alice' },
{ $set: { age: 21 } }
);
// Update many documents
await students.updateMany(
{ course: 'CSE' },
{ $set: { department: 'Computer Science' } }
);
Delete
// Delete one document
await students.deleteOne({ name: 'Bob' });
// Delete many documents
await students.deleteMany({ course: 'IT' });
Sort
// Sort by age ascending (1) or descending (-1)
const byAgeAsc = await students.find({}).sort({ age: 1 }).toArray();
const byAgeDesc = await students.find({}).sort({ age: -1 }).toArray();
Join (Aggregation with $lookup)
MongoDB is not relational, but it supports join-like operations using $lookup in the aggregation pipeline:
const results = await db.collection('orders').aggregate([
{
$lookup: {
from: 'students', // collection to join
localField: 'studentId', // field in "orders"
foreignField: '_id', // field in "students"
as: 'studentDetails'
}
}
]).toArray();
Full CRUD Example
async function run() {
const db = client.db('schoolDB');
const students = db.collection('students');
await students.insertOne({ name: 'Dave', age: 23, course: 'ECE' });
const found = await students.find({ course: 'ECE' }).sort({ age: -1 }).toArray();
await students.updateOne({ name: 'Dave' }, { $set: { age: 24 } });
await students.deleteOne({ name: 'Dave' });
console.log(found);
}
Key Takeaway: MongoDB stores flexible JSON-like documents in collections rather than rigid tables. The officialmongodbdriver exposesinsertOne/Many,find,updateOne/Many,deleteOne/Many,.sort(), and$lookup(for join-like queries) — all through simple, promise-based async calls.