← Back to MongoDB Course | Chapter 10: MongoDB with Node.js | Lesson 1 of 7

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:

  1. MongoDB Node.js driver
Syntax
javascript
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

javascript
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
  1. Creating a new client per request
  2. Forgetting await on driver calls
  3. 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:

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.