MongoDB is one of the most popular NoSQL databases, particularly known for its schema-less design and flexibility in handling large volumes of data. Understanding CRUD operations—Create, Read, Update, and Delete—is essential for anyone looking to work with MongoDB efficiently. Let’s dive into these operations and see how they work!
The Create operation is used to insert new documents into a collection. In MongoDB, documents are stored in collections, and these documents are represented in BSON (Binary JSON) format.
// Connect to your MongoDB database const MongoClient = require('mongodb').MongoClient; async function run() { const client = new MongoClient('mongodb://localhost:27017'); await client.connect(); const database = client.db('sampleDB'); const collection = database.collection('users'); // Create a new document const newUser = { name: "John Doe", age: 30, email: "john.doe@example.com" }; const result = await collection.insertOne(newUser); console.log(`New user created with the following id: ${result.insertedId}`); await client.close(); } run().catch(console.dir);
In this example, we connect to a MongoDB database named sampleDB
and insert a new user document into the users
collection. The insertOne
method returns an object containing the insertedId
, which is useful for referencing the newly created document later.
The Read operation is crucial for retrieving data from a MongoDB collection. You can fetch single or multiple documents based on different criteria using various MongoDB queries.
async function readUsers() { const client = new MongoClient('mongodb://localhost:27017'); await client.connect(); const database = client.db('sampleDB'); const collection = database.collection('users'); // Find one user const user = await collection.findOne({ name: "John Doe" }); console.log(user); // Find all users const allUsers = await collection.find({}).toArray(); console.log(allUsers); await client.close(); } readUsers().catch(console.dir);
Here, we retrieve a single user document by filtering based on the user's name. The findOne
method returns the first document that matches the specified condition. We also use find({})
with toArray()
to get all documents from the users
collection.
The Update operation allows you to modify existing documents in a MongoDB collection. You can update fields of a single document or multiple documents based on specific criteria.
async function updateUser() { const client = new MongoClient('mongodb://localhost:27017'); await client.connect(); const database = client.db('sampleDB'); const collection = database.collection('users'); // Update user age const result = await collection.updateOne( { name: "John Doe" }, { $set: { age: 31 } } ); console.log(`${result.modifiedCount} document(s) updated`); await client.close(); } updateUser().catch(console.dir);
In this example, we update the age of the user named "John Doe". The updateOne
method takes two parameters: a filter to match the document and an update operator ($set
) to specify the changes. The result includes the count of modified documents.
The Delete operation is used to remove documents from a collection. You can delete single or multiple documents based on specified conditions.
async function deleteUser() { const client = new MongoClient('mongodb://localhost:27017'); await client.connect(); const database = client.db('sampleDB'); const collection = database.collection('users'); // Delete a user const result = await collection.deleteOne({ name: "John Doe" }); console.log(`${result.deletedCount} document(s) deleted`); await client.close(); } deleteUser().catch(console.dir);
This example demonstrates how to delete a user document by matching the name "John Doe". The deleteOne
method returns the count of deleted documents, providing confirmation of the operation's success.
To summarize, we’ve covered the essential CRUD operations in MongoDB, including how to create, read, update, and delete documents in a collection. Each of these operations utilizes specific MongoDB methods and provides a straightforward approach to data manipulation. Embracing these concepts will significantly enhance your ability to work with MongoDB effectively and efficiently!
Feel free to experiment with these examples in your own MongoDB environment, and don't hesitate to dive deeper into more advanced topics as you grow your database skills!
09/11/2024 | MongoDB
09/11/2024 | MongoDB
09/11/2024 | MongoDB
09/11/2024 | MongoDB
09/11/2024 | MongoDB
09/11/2024 | MongoDB
09/11/2024 | MongoDB
09/11/2024 | MongoDB