Loading lessons...
The Node.js Driver
The Node.js Driver
Let's connect to MongoDB from a Node.js application using the official mongodb package.
Install
npm install mongodb
Connect and read
const { MongoClient } = require("mongodb");
const uri = "<Your Connection String>";
const client = new MongoClient(uri);
async function run() {
try {
await client.connect();
const db = client.db("sample_mflix");
const collection = db.collection("movies");
// Find the first document in the collection
const first = await collection.findOne();
console.log(first);
} finally {
// Always close the connection
await client.close();
}
}
run().catch(console.error);
Run it with node index.js.
The connection string
mongodb+srv://<username>:<password>@<cluster>.mongodb.net/<dbname>?retryWrites=true&w=majority
Replace <username>, <password>, and <cluster> with values from Atlas (Database → Connect → Connect your application).
The pattern
new MongoClient(uri)- create a client.client.connect()- connect.client.db(name)- pick a database.db.collection(name)- pick a collection.- Work with the collection, then
client.close()in afinallyblock.
Everything is async
Driver methods return Promises, so you use async/await.
TL;DR
- Install
mongodbwith npm. - Connect via
MongoClient+ Atlas connection string. - Always close the client in
finally; methods are async.