Node.js Tutorial
Estimated reading: 3 minutes 272 views

Node.js โ€“ MongoDB: CRUD Operations โ€“ Insert, Find, Update & Delete Documents

Introduction โ€“ Perform Core Data Operations with MongoDB & Node.js

CRUD stands for Create, Read, Update, and Deleteโ€”the foundational actions for managing application data. When using MongoDB with Node.js, these operations become intuitive, thanks to the flexible JSON-like document structure and the power of the MongoDB driver.

In this guide, youโ€™ll learn:

  • How to insert, find, update, and delete documents in MongoDB using Node.js
  • How to use MongoDB methods like insertOne, find, updateOne, and deleteOne
  • How to handle real-world data operations with examples and outputs

Topics Covered

Topic Description
Node.js โ€“ MongoDB InsertAdd new documents to a MongoDB collection
Node.js โ€“ MongoDB FindRetrieve one or multiple documents using filters
Node.js โ€“ MongoDB UpdateModify specific fields in existing documents
Node.js โ€“ MongoDB DeleteRemove documents from a collection using filters

Node.js โ€“ MongoDB Insert

insertOne Example

const client = require('./db');

async function insertEmployee() {
  const db = client.db('myCompany');
  const result = await db.collection('employees').insertOne({
    name: "Alice",
    role: "HR",
    salary: 50000
  });
  console.log("Document inserted with ID:", result.insertedId);
}

insertEmployee();

Output:

Document inserted with ID: 665faec7e45acbd2497d12f9

Use insertMany() to insert multiple documents at once.


Node.js โ€“ MongoDB Find

Find All Documents

async function findAllEmployees() {
  const db = client.db('myCompany');
  const employees = await db.collection('employees').find().toArray();
  console.log(employees);
}

findAllEmployees();

Output:

[
  { name: "Alice", role: "HR", salary: 50000 },
  { name: "Bob", role: "Developer", salary: 65000 }
]

Find with Filter

async function findByRole() {
  const db = client.db('myCompany');
  const devs = await db.collection('employees').find({ role: "Developer" }).toArray();
  console.log(devs);
}

findByRole();

Output:

[
  { name: "Bob", role: "Developer", salary: 65000 }
]

You can use query operators like $gt, $lt, $in, $and, etc.


Node.js โ€“ MongoDB Update

updateOne Example

async function updateSalary() {
  const db = client.db('myCompany');
  const result = await db.collection('employees').updateOne(
    { name: "Alice" },
    { $set: { salary: 55000 } }
  );
  console.log("Documents matched:", result.matchedCount);
  console.log("Documents modified:", result.modifiedCount);
}

updateSalary();

Output:

Documents matched: 1
Documents modified: 1

Use $inc, $unset, or $push for numeric or array field operations.


Node.js โ€“ MongoDB Delete

deleteOne Example

async function deleteEmployee() {
  const db = client.db('myCompany');
  const result = await db.collection('employees').deleteOne({ name: "Alice" });
  console.log("Documents deleted:", result.deletedCount);
}

deleteEmployee();

Output:

Documents deleted: 1

Use deleteMany() to remove multiple documents matching a condition.


Summary โ€“ Recap & Next Steps

CRUD operations form the backbone of every MongoDB application. Using Node.js, you can perform these operations in a fully asynchronous manner, allowing for real-time apps and scalable backend services.

Key Takeaways:

  • Use insertOne() or insertMany() to add data
  • Use find() with filters to query collections
  • Use updateOne() or updateMany() for updates
  • Use deleteOne() or deleteMany() to remove data

Real-World Uses:

  • User account management in REST APIs
  • Blog or CMS content creation and editing
  • Real-time data updates in dashboards
  • Transaction logs and cleanup tasks

Frequently Asked Questions

Can I use async/await with MongoDB operations?
Yes. The MongoDB driver supports Promisesโ€”ideal for async functions in Node.js.


What happens if no document matches in updateOne?
MongoDB returns matchedCount: 0, and no document is modified.


Is MongoDB case-sensitive for string queries?
Yes, unless you use a case-insensitive regex filter like { name: /alice/i }.


How do I prevent accidental mass deletions?
Always use specific filters or test queries before applying deleteMany().


Share Now :
Share

๐Ÿ—„๏ธ Node.js โ€“ MongoDB: CRUD Operations

Or Copy Link

CONTENTS
Scroll to Top