Create New Post

MongoDB - CRUD

CRUD stands for Create, Read, Update, and Delete, which are the basic operations that can be performed on any persistent storage. MongoDB, being a NoSQL database, provides a flexible and powerful set of CRUD operations. Here's an overview of how CRUD operations are implemented in MongoDB:

1. Create (Insert):

To insert documents into a MongoDB collection, you use the insertOne or insertMany method.

Example - Insert a Single Document:

db.collection_name.insertOne({
  field1: value1,
  field2: value2,
  // ... other fields
});

Example - Insert Multiple Documents:

db.collection_name.insertMany([
  { field1: value1, field2: value2 },
  { field1: value3, field2: value4 },
  // ... other documents
]);

2. Read (Query):

To retrieve documents from a MongoDB collection, you use the find method.

Example - Find All Documents:

db.collection_name.find();

Example - Find Documents Matching a Condition:

db.collection_name.find({ field: value });

Example - Find Documents with Projections (selecting specific fields):

db.collection_name.find({}).project({ field1: 1, field2: 1, _id: 0 });

Example - Find One Document:

db.collection_name.findOne({ field: value });

3. Update:

To update documents in a MongoDB collection, you use the updateOne or updateMany method.

Example - Update a Single Document:


 

db.collection_name.updateOne(
  { field: value },
  { $set: { updated_field: new_value } }
);

Example - Update Multiple Documents:

db.collection_name.updateMany(
  { field: value },
  { $set: { updated_field: new_value } }
);

4. Delete:

To remove documents from a MongoDB collection, you use the deleteOne or deleteMany method.

Example - Delete a Single Document:

db.collection_name.deleteOne({ field: value });

Example - Delete Multiple Documents:

db.collection_name.deleteMany({ field: value });

Additional Notes:

  • Upsert: The updateOne and updateMany methods can also be used with the upsert option to perform an update or insert if the document doesn't exist.

  • Atomic Operations: MongoDB provides atomic operations at the document level. Updates are atomic on a single document, even if multiple fields are modified.

  • Aggregation Framework: For complex data transformations or aggregations, MongoDB offers a powerful Aggregation Framework that allows you to pipeline multiple operations.

Comments

Leave a Reply

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

43933