Building Node.js Applications with MongoDB: A Practical Guide

Unleash the power of MongoDB in your Node.js applications! This tutorial dives deep into connecting to a MongoDB Atlas database, installing the necessary Node.js driver, and performing CRUD operations (Create, Read, Update, Delete). Learn how to interact with your data seamlessly, streamline development, and leverage the flexibility of MongoDB in your Node.js projects.



MongoDB Node.js Database Interaction

In this tutorial, we'll connect to a MongoDB Atlas database using Node.js. If you don't have a MongoDB Atlas account, you can create one for free at MongoDB Atlas.

MongoDB Node.js Driver Installation

To use MongoDB with Node.js, install the mongodb package:

npm install mongodb

Create a file named index.js in your project directory.

index.js


const { MongoClient } = require('mongodb');

Connection String

To connect to your MongoDB Atlas database, get the connection string from the Atlas dashboard:

  • Go to your Cluster and click CONNECT.
  • Select Connect your application and copy your connection string.
  • Replace <username>, <password>, and <cluster.string> with your MongoDB Atlas credentials.
const uri = "<Your Connection String>";

Connecting to MongoDB

Add the following code to your index.js file:


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 {
    // Close the database connection
    await client.close();
  }
}
run().catch(console.error);

Run the file using:

node index.js

You should see the first document logged to the console.

CRUD & Document Aggregation

Just like in mongosh, you can perform CRUD operations and aggregation using the MongoDB Node.js driver. Replace collection.findOne() with methods like find(), insertOne(), insertMany(), updateOne(), updateMany(), deleteOne(), deleteMany(), or aggregate().