Reading Documents With the Node.js Driver
Learners will connect a Node.js script to MongoDB and perform insert/find operations using the official driver.
The Official Node.js Driver
The MongoDB Node.js driver (mongodb npm package) is the official, low-level client for connecting to MongoDB from Node.js. It is maintained by MongoDB Inc., supports the full MongoDB API, and ships with TypeScript type definitions.
The driver exposes a MongoClient class that manages a connection pool—a set of pre-established TCP connections reused across requests. This eliminates the overhead of creating a new connection for every operation. Most production Node.js apps share a single MongoClient instance for the lifetime of the process.
# Install the MongoDB Node.js driver
npm install mongodb
# TypeScript types are included - no @types/mongodb neededCreating a MongoClient and Connecting
Create a MongoClient with your connection string URI and call connect(). The connection is not established until connect() (or the first operation). Once connected, retrieve a database reference with client.db('dbName') and a collection reference with db.collection('collName').
Best practice: create the MongoClient once at application startup and export/inject it. Do NOT create a new client per request—this exhausts file descriptors and defeats the connection pool.
const { MongoClient } = require('mongodb');
const uri = process.env.MONGODB_URI || 'mongodb://localhost:27017';
const client = new MongoClient(uri);
async function main() {
await client.connect();
console.log('Connected to MongoDB');
const db = client.db('myapp');
const users = db.collection('users');
// ... perform operations ...
await client.close();
}
main().catch(console.error);All lessons in this course
- insertOne and insertMany
- findOne vs find: Cursors Explained
- Querying Nested Fields and Arrays
- Reading Documents With the Node.js Driver