MongoDB Node.js driver
The official mongodb package lets Node.js programs connect to MongoDB and run the same operations as the shell.
In this page:
Syntax
const { MongoClient } = require('mongodb');
const client = new MongoClient(connectionString);
await client.connect();
const collection = client.db('database').collection('collection_name');
const docs = await collection.find(filter).toArray();
MongoDB Node.js driver
Install with npm install mongodb, create a MongoClient with a connection string, call connect, get a database and collection, then use methods such as insertOne, find(...).toArray() and updateOne, all returning promises.
Close the client when finished, or reuse one client for the app's lifetime.
Note:
Create one MongoClient per application and reuse it.
Example: MongoDB Node.js driver
const { MongoClient } = require("mongodb");
async function main() {
const client = new MongoClient(process.env.MONGODB_URI);
await client.connect();
const users = client.db("shop").collection("users");
await users.insertOne({ name: "Ada", age: 36 });
const adults = await users.find({ age: { $gte: 18 } }).toArray();
console.log(adults.length); // 1
await client.close();
}
main().catch(console.error);
⚠️ Run this in your own terminal or Node.js environment.
Related Topics
Common Mistakes
- Creating a new client per request
- Forgetting await on driver calls
- Not closing the client in scripts
Chapter Summary
- npm install mongodb
- MongoClient connects
- Collection methods return promises
- Reuse one client
🔒
Chapter Quiz — Complete all 7 topics to unlock
0/7 topics done
Complete these topics first: