Node.js MongoDB Examples

Node.js MongoDB integration lets a Node.js application store, read, update, and delete JSON-like documents in a MongoDB database. In this tutorial, we shall learn how MongoDB fits into a Node.js application, what you need before connecting, and which MongoDB driver methods are commonly used in JavaScript examples.

MongoDB stores data as documents inside collections. In Node.js, you usually work with MongoDB through the official MongoDB Node.js driver. The driver gives JavaScript methods such as connect(), db(), collection(), insertOne(), find(), updateOne(), and deleteOne().

Prerequisites to work with MongoDB from Node.js

1. Make Sure MongoDB is installed. If not Install MongoDB.

You may use either a local MongoDB server or a hosted MongoDB database such as MongoDB Atlas. For a local setup, keep the MongoDB service running before you execute the Node.js program.

2. Install “mongodb” package using npm (if not installed already).

arjun@nodejs:~/workspace/nodejs/mongodb$ npm install mongodb
npm WARN saveError ENOENT: no such file or directory, open '/home/arjun/workspace/nodejs/package.json'
npm WARN enoent ENOENT: no such file or directory, open '/home/arjun/workspace/nodejs/package.json'
npm WARN nodejs No description
npm WARN nodejs No repository field.
npm WARN nodejs No README data
npm WARN nodejs No license field.

+ mongodb@2.2.33
added 9 packages in 9.416s

The command above is kept as the original installation example. In a new Node.js project, create a package.json first and then install the MongoDB driver.

</>
Copy
mkdir node-mongodb-example
cd node-mongodb-example
npm init -y
npm install mongodb

Node.js MongoDB connection example using MongoClient

The main class used to connect Node.js with MongoDB is MongoClient. The following example connects to a local MongoDB server, opens a database named school, reads a collection named students, and closes the connection safely.

</>
Copy
const { MongoClient } = require('mongodb');

const uri = 'mongodb://127.0.0.1:27017';
const client = new MongoClient(uri);

async function main() {
  try {
    await client.connect();

    const database = client.db('school');
    const students = database.collection('students');

    const firstStudent = await students.findOne({});
    console.log(firstStudent);
  } catch (error) {
    console.error('MongoDB error:', error);
  } finally {
    await client.close();
  }
}

main();

If you use MongoDB Atlas, replace the local URI with the connection string from your Atlas cluster. Avoid hard-coding production credentials directly in source files. Store the URI in an environment variable instead.

</>
Copy
const { MongoClient } = require('mongodb');

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

MongoDB database, collection, and document example in Node.js

A MongoDB database contains collections. A collection contains documents. A document is similar to a JavaScript object and is stored in BSON format internally.

</>
Copy
{
  "name": "Ravi",
  "course": "Node.js",
  "score": 86,
  "active": true
}

In a relational database, this may look like a row in a table. In MongoDB, it is a document in a collection. The flexible document structure is useful when records do not all have exactly the same fields.

Common MongoDB Node.js driver methods for CRUD operations

The following table shows commonly used MongoDB methods in Node.js applications.

MongoDB Node.js methodPurposeTypical use
connect()Opens a connection to MongoDBStart database access from a Node.js app
db()Selects a databaseUse client.db('school')
collection()Selects a collectionUse db.collection('students')
insertOne()Inserts one documentAdd one record
insertMany()Inserts multiple documentsAdd many records at once
findOne()Reads one matching documentFetch a single record
find()Reads multiple matching documentsQuery a collection
updateOne()Updates one matching documentModify one record
deleteOne()Deletes one matching documentRemove one record

Insert documents into MongoDB from Node.js

Use insertOne() to insert a single document into a MongoDB collection.

</>
Copy
const { MongoClient } = require('mongodb');

const uri = 'mongodb://127.0.0.1:27017';
const client = new MongoClient(uri);

async function insertStudent() {
  try {
    await client.connect();

    const students = client.db('school').collection('students');

    const result = await students.insertOne({
      name: 'Ravi',
      course: 'Node.js',
      score: 86,
      active: true
    });

    console.log('Inserted document id:', result.insertedId);
  } finally {
    await client.close();
  }
}

insertStudent();

Use insertMany() when you need to add multiple documents in one operation.

</>
Copy
await students.insertMany([
  { name: 'Anita', course: 'MongoDB', score: 91 },
  { name: 'Kiran', course: 'Node.js', score: 78 }
]);

Query MongoDB documents in a Node.js application

Use findOne() when you expect one document. Use find() when you need a list of documents.

</>
Copy
const student = await students.findOne({ name: 'Ravi' });
console.log(student);

The find() method returns a cursor. Convert it to an array for small result sets, or iterate through it for larger result sets.

</>
Copy
const nodeStudents = await students
  .find({ course: 'Node.js' })
  .sort({ score: -1 })
  .toArray();

console.log(nodeStudents);

Update MongoDB documents using Node.js

Use updateOne() to update the first document that matches a filter. The $set operator changes only the specified fields.

</>
Copy
const result = await students.updateOne(
  { name: 'Ravi' },
  { $set: { score: 89, active: true } }
);

console.log('Matched:', result.matchedCount);
console.log('Modified:', result.modifiedCount);

For multiple matching documents, use updateMany(). Always use a clear filter so that you do not update more documents than intended.

Delete MongoDB documents from Node.js

Use deleteOne() to remove one matching document from a collection.

</>
Copy
const result = await students.deleteOne({ name: 'Ravi' });

console.log('Deleted:', result.deletedCount);

For multiple matching documents, use deleteMany(). Be careful with empty filters because an empty filter can match all documents in a collection.

Complete Node.js MongoDB CRUD example

The following program connects to MongoDB, inserts a document, reads it, updates it, deletes it, and closes the connection.

</>
Copy
const { MongoClient } = require('mongodb');

const uri = 'mongodb://127.0.0.1:27017';
const client = new MongoClient(uri);

async function runCrudExample() {
  try {
    await client.connect();

    const students = client.db('school').collection('students');

    const insertResult = await students.insertOne({
      name: 'Meena',
      course: 'Node.js MongoDB',
      score: 82
    });
    console.log('Inserted:', insertResult.insertedId);

    const savedStudent = await students.findOne({ name: 'Meena' });
    console.log('Found:', savedStudent);

    const updateResult = await students.updateOne(
      { name: 'Meena' },
      { $set: { score: 88 } }
    );
    console.log('Updated:', updateResult.modifiedCount);

    const deleteResult = await students.deleteOne({ name: 'Meena' });
    console.log('Deleted:', deleteResult.deletedCount);
  } catch (error) {
    console.error(error);
  } finally {
    await client.close();
  }
}

runCrudExample();

Node.js MongoDB Tutorial Index

After learning how to connect a Node.js application to MongoDB, continue with the following MongoDB examples.

Node.js MongoDB connection troubleshooting

If the Node.js program cannot connect to MongoDB, check the following items before changing the application code.

  • Confirm that the MongoDB server is running.
  • Check whether the connection string uses the correct host, port, username, password, and database options.
  • For local MongoDB, try mongodb://127.0.0.1:27017 instead of mongodb://localhost:27017 if there is a DNS or IPv6 resolution issue.
  • For MongoDB Atlas, verify that your current IP address is allowed in the network access settings.
  • Do not close the MongoDB client before awaited database operations finish.

Node.js MongoDB editorial QA checklist

  • Verify that every MongoDB code example imports MongoClient correctly.
  • Check that connection strings do not expose real usernames, passwords, or production hosts.
  • Confirm that insert, find, update, and delete examples use awaited asynchronous calls.
  • Make sure destructive examples such as deleteMany() include a warning about filters.
  • Test the examples against a local MongoDB instance or a safe development database before publishing changes.

Node.js MongoDB FAQs

What is MongoDB with a Node.js example?

MongoDB is a document database that stores data as documents inside collections. In Node.js, you can connect to MongoDB with MongoClient, choose a database with db(), choose a collection with collection(), and then use methods such as insertOne() or find().

How do I use MongoDB in JavaScript?

Install the mongodb package with npm, import MongoClient, connect using a MongoDB URI, select a database and collection, and call CRUD methods. In Node.js, these operations are asynchronous, so use async and await.

What are the common MongoDB methods used in Node.js?

Common methods include connect(), db(), collection(), insertOne(), insertMany(), findOne(), find(), updateOne(), updateMany(), deleteOne(), and deleteMany().

Should I open and close a MongoDB connection for every query in Node.js?

For small scripts, opening and closing the client inside the script is acceptable. For a server application, it is usually better to create the MongoDB client once, reuse it across requests, and close it only when the application shuts down.

Can Node.js create a MongoDB database automatically?

Yes. MongoDB creates a database when you first store data in it. Selecting a database with client.db('name') alone does not create stored data. The database appears after you create a collection or insert documents.

References for Node.js MongoDB examples

MongoDB Tutorial – Learn Basics of MongoDB with Examples.

You may also refer to the official MongoDB Node.js driver documentation for driver-specific options, authentication settings, and current API details.

Conclusion: using MongoDB with Node.js applications

In this Node.js Tutorial – Node.js MongoDB, we have learnt to interface MongoDB Database with Node.js Applications using examples. We covered the required npm package, the MongoClient connection flow, basic document structure, and common CRUD operations used in Node.js MongoDB programs.