MongoDB Drivers
Drivers are language-specific libraries that let your application code connect to MongoDB and run queries, using the Node.js driver as the running example.
What a Driver Does
The mongosh shell is great for exploring data interactively, but real applications talk to MongoDB through a driver — an official library for a specific programming language (Node.js, Python, Java, C#, Go, and more) that handles the network protocol, connection pooling, and translates native data structures into BSON documents and back. MongoDB maintains official drivers for every major language, so the concepts you learn with one driver transfer easily to another.
Installing and Connecting with the Node.js Driver
The official Node.js driver is published as the mongodb package on npm. After installing it, you create a MongoClient, connect, and grab a reference to a database and collection.
Connect to MongoDB from Node.js
// npm install mongodb
const { MongoClient } = require("mongodb");
const uri = "mongodb://localhost:27017";
const client = new MongoClient(uri);
async function main() {
await client.connect();
const db = client.db("shop");
const products = db.collection("products");
console.log("Connected to MongoDB");
return products;
}
main().catch(console.error);Running Queries from Application Code
Once you have a collection object, the driver's methods mirror the shell almost exactly: find(), insertOne(), updateOne(), and deleteOne() all exist, but they return Promises in Node.js, so you use async/await to work with the results.
Insert and query documents
async function run() {
await client.connect();
const products = client.db("shop").collection("products");
await products.insertOne({ name: "Keyboard", price: 45 });
const cursor = products.find({ price: { $lt: 100 } });
const results = await cursor.toArray();
console.log(results);
await client.close();
}
run().catch(console.error);Managing Connections Properly
A MongoClient instance manages a pool of connections internally, so it should be created once per application and reused, not opened and closed for every single query. Closing and reopening connections constantly adds latency and can exhaust the connection pool under load.
Reuse a single client across requests
const client = new MongoClient(uri);
let dbConnection;
async function connectToDb() {
if (!dbConnection) {
await client.connect();
dbConnection = client.db("shop");
}
return dbConnection;
}
module.exports = { connectToDb };- MongoClient — the entry point that manages the connection pool.
- db.collection(name) — gets a reference to a collection to query.
- Async methods — find, insertOne, updateOne, deleteOne all return Promises in Node.js.
- Connection string (URI) — specifies host, port, and optional credentials/database.
- client.close() — releases the connection pool when your application shuts down.
Exercise: MongoDB Drivers
What is the main purpose of a MongoDB driver?