MongoDB - Performing CRUD Operations

Performing CRUD Operations in MongoDB 

Introduction to MongoDB CRUD Operations

MongoDB is one of the most popular NoSQL databases used for building scalable and high-performance applications. It stores data in flexible, JSON-like documents instead of traditional tables. One of the core concepts in MongoDB is CRUD operations, which stands for Create, Read, Update, and Delete.

Understanding MongoDB CRUD operations is essential for developers working with modern web applications, backend systems, and data-driven platforms. These operations allow you to interact with the database efficiently and manage your data lifecycle.

What are CRUD Operations in MongoDB?

CRUD operations represent the four basic operations performed on any database:

  • Create: Insert new data into the database
  • Read: Retrieve data from the database
  • Update: Modify existing data
  • Delete: Remove data from the database

In MongoDB, these operations are performed using collections and documents. A collection is similar to a table in relational databases, while a document is similar to a row.

MongoDB Create Operations

Introduction to Create Operation

The Create operation in MongoDB is used to insert new documents into a collection. MongoDB automatically creates a collection if it does not exist when inserting a document.

Insert One Document

The insertOne() method is used to insert a single document into a collection.

db.users.insertOne({
  name: "John Doe",
  age: 28,
  email: "john@example.com",
  isActive: true
});

This command inserts one document into the "users" collection. If the collection does not exist, MongoDB creates it automatically.

Insert Multiple Documents

To insert multiple documents at once, MongoDB provides the insertMany() method.

db.users.insertMany([
  { name: "Alice", age: 25, email: "alice@example.com" },
  { name: "Bob", age: 30, email: "bob@example.com" },
  { name: "Charlie", age: 35, email: "charlie@example.com" }
]);

This method improves performance by inserting multiple records in a single operation.

Understanding Document Structure

Documents in MongoDB are stored in BSON format, which is a binary representation of JSON. Each document has a unique _id field that acts as a primary key.

MongoDB Read Operations

Introduction to Read Operation

The Read operation retrieves data from MongoDB collections. MongoDB provides flexible querying capabilities using the find() and findOne() methods.

Find All Documents

db.users.find();

This command retrieves all documents from the "users" collection.

Find Specific Document

db.users.findOne({ name: "Alice" });

This returns the first document that matches the query condition.

Query with Conditions

db.users.find({ age: { $gt: 25 } });

This query retrieves all users whose age is greater than 25.

Using Projection

db.users.find(
  { age: { $gt: 25 } },
  { name: 1, email: 1, _id: 0 }
);

Projection allows you to include or exclude specific fields in the result.

Comparison Operators

  • $gt - Greater than
  • $lt - Less than
  • $gte - Greater than or equal
  • $lte - Less than or equal
  • $eq - Equal
  • $ne - Not equal

Logical Operators

db.users.find({
  $and: [
    { age: { $gt: 25 } },
    { isActive: true }
  ]
});

Logical operators such as $and, $or, and $not help in building complex queries.

MongoDB Update Operations

Introduction to Update Operation

The Update operation modifies existing documents in a collection. MongoDB provides multiple methods to update documents efficiently.

Update One Document

db.users.updateOne(
  { name: "Alice" },
  { $set: { age: 26 } }
);

This updates the age of the user named Alice.

Update Multiple Documents

db.users.updateMany(
  { isActive: true },
  { $set: { status: "active" } }
);

This updates all documents where isActive is true.

Replace Document

db.users.replaceOne(
  { name: "Bob" },
  { name: "Bob", age: 32, email: "bob_new@example.com" }
);

This completely replaces the existing document.

Update Operators

  • $set - Sets a field value
  • $unset - Removes a field
  • $inc - Increments a value
  • $push - Adds value to an array
  • $pull - Removes value from an array

Increment Example

db.users.updateOne(
  { name: "John Doe" },
  { $inc: { age: 1 } }
);

This increases the age by 1.

MongoDB Delete Operations

Introduction to Delete Operation

The Delete operation removes documents from a collection. MongoDB provides flexible options for deleting one or multiple documents.

Delete One Document

db.users.deleteOne({ name: "Charlie" });

This deletes the first document that matches the condition.

Delete Multiple Documents

db.users.deleteMany({ age: { $lt: 25 } });

This deletes all documents where age is less than 25.

Delete All Documents

db.users.deleteMany({});

This removes all documents from the collection but keeps the collection intact.

Advanced CRUD Techniques

Upsert Operation

Upsert is a combination of update and insert. If a document does not exist, MongoDB inserts it.

db.users.updateOne(
  { name: "David" },
  { $set: { age: 40 } },
  { upsert: true }
);

Bulk Write Operations

db.users.bulkWrite([
  {
    insertOne: {
      document: { name: "Eve", age: 22 }
    }
  },
  {
    updateOne: {
      filter: { name: "Alice" },
      update: { $set: { age: 27 } }
    }
  },
  {
    deleteOne: {
      filter: { name: "Bob" }
    }
  }
]);

Bulk operations improve performance by combining multiple operations.

MongoDB CRUD operations form the foundation of working with MongoDB databases. By mastering Create, Read, Update, and Delete operations, developers can efficiently manage and manipulate data in modern applications.

With flexible schema design, powerful querying capabilities, and scalability, MongoDB is a preferred choice for developers worldwide. Practicing CRUD operations regularly will help you build robust and efficient applications.

Beginner 5 Hours

Performing CRUD Operations in MongoDB 

Introduction to MongoDB CRUD Operations

MongoDB is one of the most popular NoSQL databases used for building scalable and high-performance applications. It stores data in flexible, JSON-like documents instead of traditional tables. One of the core concepts in MongoDB is CRUD operations, which stands for Create, Read, Update, and Delete.

Understanding MongoDB CRUD operations is essential for developers working with modern web applications, backend systems, and data-driven platforms. These operations allow you to interact with the database efficiently and manage your data lifecycle.

What are CRUD Operations in MongoDB?

CRUD operations represent the four basic operations performed on any database:

  • Create: Insert new data into the database
  • Read: Retrieve data from the database
  • Update: Modify existing data
  • Delete: Remove data from the database

In MongoDB, these operations are performed using collections and documents. A collection is similar to a table in relational databases, while a document is similar to a row.

MongoDB Create Operations

Introduction to Create Operation

The Create operation in MongoDB is used to insert new documents into a collection. MongoDB automatically creates a collection if it does not exist when inserting a document.

Insert One Document

The insertOne() method is used to insert a single document into a collection.

db.users.insertOne({ name: "John Doe", age: 28, email: "john@example.com", isActive: true });

This command inserts one document into the "users" collection. If the collection does not exist, MongoDB creates it automatically.

Insert Multiple Documents

To insert multiple documents at once, MongoDB provides the insertMany() method.

db.users.insertMany([ { name: "Alice", age: 25, email: "alice@example.com" }, { name: "Bob", age: 30, email: "bob@example.com" }, { name: "Charlie", age: 35, email: "charlie@example.com" } ]);

This method improves performance by inserting multiple records in a single operation.

Understanding Document Structure

Documents in MongoDB are stored in BSON format, which is a binary representation of JSON. Each document has a unique _id field that acts as a primary key.

MongoDB Read Operations

Introduction to Read Operation

The Read operation retrieves data from MongoDB collections. MongoDB provides flexible querying capabilities using the find() and findOne() methods.

Find All Documents

db.users.find();

This command retrieves all documents from the "users" collection.

Find Specific Document

db.users.findOne({ name: "Alice" });

This returns the first document that matches the query condition.

Query with Conditions

db.users.find({ age: { $gt: 25 } });

This query retrieves all users whose age is greater than 25.

Using Projection

db.users.find( { age: { $gt: 25 } }, { name: 1, email: 1, _id: 0 } );

Projection allows you to include or exclude specific fields in the result.

Comparison Operators

  • $gt - Greater than
  • $lt - Less than
  • $gte - Greater than or equal
  • $lte - Less than or equal
  • $eq - Equal
  • $ne - Not equal

Logical Operators

db.users.find({ $and: [ { age: { $gt: 25 } }, { isActive: true } ] });

Logical operators such as $and, $or, and $not help in building complex queries.

MongoDB Update Operations

Introduction to Update Operation

The Update operation modifies existing documents in a collection. MongoDB provides multiple methods to update documents efficiently.

Update One Document

db.users.updateOne( { name: "Alice" }, { $set: { age: 26 } } );

This updates the age of the user named Alice.

Update Multiple Documents

db.users.updateMany( { isActive: true }, { $set: { status: "active" } } );

This updates all documents where isActive is true.

Replace Document

db.users.replaceOne( { name: "Bob" }, { name: "Bob", age: 32, email: "bob_new@example.com" } );

This completely replaces the existing document.

Update Operators

  • $set - Sets a field value
  • $unset - Removes a field
  • $inc - Increments a value
  • $push - Adds value to an array
  • $pull - Removes value from an array

Increment Example

db.users.updateOne( { name: "John Doe" }, { $inc: { age: 1 } } );

This increases the age by 1.

MongoDB Delete Operations

Introduction to Delete Operation

The Delete operation removes documents from a collection. MongoDB provides flexible options for deleting one or multiple documents.

Delete One Document

db.users.deleteOne({ name: "Charlie" });

This deletes the first document that matches the condition.

Delete Multiple Documents

db.users.deleteMany({ age: { $lt: 25 } });

This deletes all documents where age is less than 25.

Delete All Documents

db.users.deleteMany({});

This removes all documents from the collection but keeps the collection intact.

Advanced CRUD Techniques

Upsert Operation

Upsert is a combination of update and insert. If a document does not exist, MongoDB inserts it.

db.users.updateOne( { name: "David" }, { $set: { age: 40 } }, { upsert: true } );

Bulk Write Operations

db.users.bulkWrite([ { insertOne: { document: { name: "Eve", age: 22 } } }, { updateOne: { filter: { name: "Alice" }, update: { $set: { age: 27 } } } }, { deleteOne: { filter: { name: "Bob" } } } ]);

Bulk operations improve performance by combining multiple operations.

MongoDB CRUD operations form the foundation of working with MongoDB databases. By mastering Create, Read, Update, and Delete operations, developers can efficiently manage and manipulate data in modern applications.

With flexible schema design, powerful querying capabilities, and scalability, MongoDB is a preferred choice for developers worldwide. Practicing CRUD operations regularly will help you build robust and efficient applications.

Related Tutorials

Frequently Asked Questions for Node.js

A function passed as an argument and executed later.

Runs multiple instances to utilize multi-core systems.

Reusable blocks of code, exported and imported using require() or import.

nextTick() executes before setImmediate() in the event loop.

Starts a server and listens on specified port.

Node Package Manager β€” installs, manages, and shares JavaScript packages.

A minimal and flexible web application framework for Node.js.

A stream handles reading or writing data continuously.

It processes asynchronous callbacks and non-blocking I/O operations efficiently.

Node.js is a JavaScript runtime built on Chrome's V8 engine for server-side scripting.

An object representing the eventual completion or failure of an asynchronous operation.

require is CommonJS; import is ES6 syntax (requires transpilation or newer versions).

Use module.exports or exports.functionName.

Variables stored outside the code for configuration, accessed using process.env.


MongoDB, often used with Mongoose for schema management.

Describes project details and manages dependencies and scripts.

Synchronous blocks execution; asynchronous runs in background without blocking.

Allows or restricts resources shared between different origins.

Use try-catch, error events, or middleware for error handling.

Provides file system-related operations like read, write, delete.

Using event-driven architecture and non-blocking I/O.

Functions in Express that execute during request-response cycle.

A set of routes or endpoints to interact with server logic or databases.

Yes, it's single-threaded but handles concurrency using the event loop and asynchronous callbacks.

Middleware to parse incoming request bodies, like JSON or form data.

line

Copyrights © 2024 letsupdateskills All rights reserved