CRUD Operations in MongoDB
1. Introduction
CRUD operations are the four basic functions of persistent storage. In MongoDB, which is a NoSQL database, these operations allow you to Create, Read, Update, and Delete documents in your collections.
2. CRUD Overview
The basic operations can be summarized as follows:
- Create: Inserting new documents into collections.
- Read: Retrieving documents from collections.
- Update: Modifying existing documents.
- Delete: Removing documents from collections.
3. Create Operation
To create a new document in a MongoDB collection, you use the insertOne()
or insertMany()
methods.
const { MongoClient } = require('mongodb');
async function run() {
const client = new MongoClient('mongodb://localhost:27017');
await client.connect();
const database = client.db('sampleDB');
const collection = database.collection('users');
// Insert a single document
const singleUser = { name: "John Doe", age: 25 };
const result = await collection.insertOne(singleUser);
console.log(`A document was inserted with the _id: ${result.insertedId}`);
// Insert multiple documents
const multipleUsers = [
{ name: "Alice", age: 30 },
{ name: "Bob", age: 22 }
];
const insertManyResult = await collection.insertMany(multipleUsers);
console.log(`${insertManyResult.insertedCount} documents were inserted.`);
}
run().catch(console.dir);
4. Read Operation
To read documents from a MongoDB collection, you can use the find()
method which returns a cursor to the documents in the collection.
async function readDocuments() {
const cursor = collection.find();
await cursor.forEach(doc => console.log(doc));
}
5. Update Operation
Updating documents can be done using the updateOne()
or updateMany()
methods.
async function updateDocument() {
const updateResult = await collection.updateOne(
{ name: "John Doe" },
{ $set: { age: 26 } }
);
console.log(`${updateResult.modifiedCount} document(s) was/were updated.`);
}
6. Delete Operation
To delete documents, you can use the deleteOne()
or deleteMany()
methods.
async function deleteDocument() {
const deleteResult = await collection.deleteOne({ name: "John Doe" });
console.log(`${deleteResult.deletedCount} document(s) was/were deleted.`);
}
7. Best Practices
When performing CRUD operations in MongoDB, consider the following best practices:
- Always validate input data before performing operations.
- Use indexes to improve read performance.
- Handle errors and exceptions gracefully.
- Monitor the performance of your queries.
8. FAQ
What is the difference between insertOne() and insertMany()?
insertOne() is used to insert a single document while insertMany() is used to insert multiple documents in one operation.
Can I update multiple documents at once?
Yes, you can use the updateMany()
method to update multiple documents that match a specified filter.
What happens if I try to delete a document that does not exist?
If you attempt to delete a document that does not exist, MongoDB will not throw an error. The result will indicate that no documents were deleted.