Node.js Tutorial
Estimated reading: 3 minutes 25 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 :

Leave a Reply

Your email address will not be published. Required fields are marked *

Share

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

Or Copy Link

CONTENTS
Scroll to Top