MongoDB CRUD Operations
CRUD operations form the foundation of interacting with a MongoDB collection.
MongoDB CRUD operations refer to the fundamental operations used to manage data in a MongoDB database. CRUD stands for Create, Read, Update, and Delete, and these operations form the basis of interacting with a MongoDB collection.
MongoDB CRUD Operations
MongoDB CRUD operations refer to the fundamental operations used to manage data in a MongoDB database. CRUD stands for Create, Read, Update, and Delete, and these operations form the basis of interacting with a MongoDB collection.
Create
The insertOne()
method is used to create a new document in a MongoDB collection.
db.collectionName.insertOne({ name: "John Doe", age: 30 });
Read
The find()
method is used to retrieve documents from a collection. You can filter documents using query conditions.
db.collectionName.find({ age: { $gt: 25 } }); // Find documents where age is greater than 25
Update
The updateOne()
method is used to update a single document in a collection. The updateMany()
method updates multiple documents.
db.collectionName.updateOne({ name: "John Doe" }, { $set: { age: 35 } }); // Update the document where name is "John Doe"
Delete
The deleteOne()
method is used to delete a single document from a collection. The deleteMany()
method deletes multiple documents.
db.collectionName.deleteOne({ name: "John Doe" }); // Delete the document where name is "John Doe"
Do You Know?
MongoDB uses a document-oriented model, meaning data is stored in JSON-like documents. These documents are grouped into collections.
Avoid This
Avoid using the save()
method for updating documents as it can lead to unexpected behavior, especially in concurrent scenarios.
Important Note
MongoDB CRUD operations can be performed using the MongoDB shell (mongo
) or using a driver in your application code.
Summary
- CRUD operations form the foundation of interacting with a MongoDB collection.
- Use
insertOne()
for creating documents,find()
for reading documents,updateOne()
for updating single documents, anddeleteOne()
for deleting single documents. - MongoDB's document-oriented model provides flexibility and scalability for managing data.