CodingNic

Introduction to MongoDB and the Node.js Driver

Exercises

Introduction to MongoDB and the Node.js Driver 25 min read

Exercises

Objectives

By the end of this lesson, you should be able to:

  • Set up a full Node.js-to-MongoDB connection from scratch
  • Perform a complete set of CRUD operations against a real collection
  • Compare MongoDB’s driver API directly against pg from the PostgreSQL half of this course

⚠️ A note on verification: as throughout this module, this course’s own tooling has no route to a local MongoDB server, so the expected output below reflects the official driver’s stable, documented behavior rather than this course’s own live execution. Run every step yourself, on your own machine, against a real MongoDB server.

Exercise: A Movie Collection

a) Set up. Create a new project, movies-mongo, install mongodb, and connect with MongoClient to a media database.

b) Insert documents. Insert three movies into a movies collection, each with title, year, and genre fields.

c) Read them back. Fetch all movies with find({}).toArray(), and confirm all three appear.

d) Filter. Fetch only movies from a specific genre.

e) Update one. Use updateOne and $set to correct one movie’s year, and confirm modifiedCount is 1.

f) Update many. Add a watched: false field to every movie at once with updateMany and $set.

g) Delete one. Remove one movie with deleteOne, and confirm it no longer appears in a subsequent find.

h) Compare to pg. Write a short comparison, in your own words, of students.insertOne({...}) against pool.query('INSERT INTO students...') from Module 1. What’s different about how each one returns the created record’s identifier?

Recap

This module covered MongoDB’s document model, connecting with the native driver, and the same four CRUD operations covered with raw SQL in Modules 1 and 2, now working against documents and collections instead of rows and tables.

Next module: Mongoose, adding schemas and validation on top of the driver covered here.