MongoDB with Node.js

Use the official driver in a Node.js app.

✍️ 2 exercises in this lesson
  1. Install the driver: npm install mongodb (or use the Mongoose library for schemas).
  2. Connect with new MongoClient(uri).
  3. Use the same methods as in the shell: insertOne, find, updateOne…
Keep your connection string in an environment variable, never in your code.

Key Takeaways: MongoDB with Node.js

Mastering MongoDB with Node.js helps you write clean and reliable MongoDB code. Follow standard conventions, test edge cases, and keep logic simple. Try running the code example below and complete the exercises to build confidence.

MongoDB with Node.js Code Example

MongoDB
import { MongoClient } from "mongodb";

const client = new MongoClient(process.env.MONGODB_URI);
await client.connect();

const students = client.db("school").collection("students");
await students.insertOne({ name: "Hina", city: "Multan", marks: 88 });

const top = await students.find({ marks: { $gte: 85 } }).sort({ marks: -1 }).toArray();
console.log(top.map(s => s.name));

await client.close();
Output
[ 'Sara', 'Hina' ]
Run this example on your own computer. The "Get Started" lesson shows how to set it up.

MongoDB with Node.js Practice Exercises

Check what you learned in “MongoDB with Node.js”.

/ 2 solved
Fill in the blank

Install the official MongoDB driver.

npm install 
✓ Correct! Not quite. Try again.
Multiple choice

Where should the MongoDB connection string be stored?

✓ Correct! Not quite. Try again.
to save your exercise progress.
Finished this lesson?
Mark it complete to track your progress.

Stuck on something?

Ask the community in the CodesInTech forum.

Need a developer?

Learning on your own is great — and when you need professional help, our team builds custom software, websites and mobile apps for clients worldwide.

Explore Our Services