MongoDB is a document-oriented NoSQL database that stores records as flexible JSON-like BSON documents inside collections rather than rigid rows across SQL tables. Because JavaScript objects map directly to MongoDB documents, Node.js and MongoDB pair naturally for fast-evolving APIs, catalogs, and event logs.
Comparing MongoDB terms to SQL helps map familiar database concepts immediately.
| SQL Concept | MongoDB Equivalent |
|---|---|
| Database | Database |
| Table | Collection |
| Row | Document ({ _id, ... }) |
| Column | Field |
| Primary Key | _id (ObjectId by default) |
Unlike strict SQL tables, documents in the same MongoDB collection can hold nested sub-documents and arrays (like embedding tags or shippingAddress right inside an order), reducing joins for read-heavy workloads.
Install the official mongodb driver (npm install mongodb), create one shared MongoClient instance at startup, and reuse its built-in connection pool across your application instead of connecting per request.
import { MongoClient } from 'mongodb';
const uri = process.env.MONGODB_URI || 'mongodb://127.0.0.1:27017';
const client = new MongoClient(uri, {
maxPoolSize: 20,
serverSelectionTimeoutMS: 5000,
});
async function pingMongo() {
try {
await client.connect();
await client.db('kodersolution_app').command({ ping: 1 });
console.log('Connected to MongoDB cleanly.');
} finally {
await client.close();
}
}
pingMongo().catch((err) => console.error('MongoDB error:', err.message));
new MongoClient() inside every Express route: Reconnecting per request exhausts sockets and adds TLS/handshake latency. Connect once at server boot and reuse client.db(...).ObjectId with plain strings: Querying { _id: '65f...' } fails to match a document whose _id is an ObjectId. Convert valid 24-hex strings using new ObjectId(id) first.mongodb driver or Mongoose?Use the official mongodb driver for minimal overhead, direct aggregation control, and TypeScript generics; choose Mongoose if you want built-in schema validation, hooks, and model classes.
_id in every MongoDB document?_id is a mandatory unique primary key per document. If you omit it during insertion, the Node.js driver generates a 12-byte ObjectId automatically.
Yes. On replica sets (including MongoDB Atlas), client.startSession() supports ACID transactions across multiple collections when needed.
Sign in to track your learning journey, earn industry-recognized certificates, and join our elite developer community.
Quick Access With
Experiment with the code from this lesson in our interactive playground.