Loading...

MongoDB CRUD Operations tutorial to Create, Read, Update, and Delete Data

MongoDB is a powerful and flexible NoSQL database management system that provides a scalable, high-performance solution for handling large volumes of data. It uses a document-oriented model, which allows developers to store and manipulate data in a more intuitive and flexible manner compared to traditional relational databases. In this tutorial, we will explore MongoDB's CRUD (Create, Read, Update, and Delete) operations, which are the foundation of any application that interacts with a database. We will demonstrate these operations using simple examples and provide explanations to help you better understand the concepts behind them. This tutorial is suitable for beginners and assumes no prior knowledge of MongoDB or NoSQL databases.

Prerequisites

Before diving into the tutorial, make sure you have MongoDB installed on your machine. You can download the latest version of MongoDB from the official MongoDB website. Additionally, ensure you have a MongoDB client installed, such as MongoDB Compass or Robo 3T, which will allow you to visualize and interact with your MongoDB database.

Connecting to MongoDB

To start working with MongoDB, we first need to establish a connection to the database. In this tutorial, we will be using the MongoDB Node.js driver to connect to our database. Make sure you have Node.js installed on your system and create a new directory for your project. Inside the project directory, run the following command to initialize a new Node.js project:

npm init -y

Next, install the MongoDB Node.js driver using the following command:

npm install mongodb

Now, create an index.js file in your project directory and add the following code to establish a connection to your MongoDB server:

const { MongoClient } = require('mongodb'); async function main() { const uri = 'mongodb://localhost:27017'; const client = new MongoClient(uri, { useUnifiedTopology: true }); try { await client.connect(); console.log('Connected to MongoDB'); } catch (error) { console.error('Error connecting to MongoDB:', error); } finally { await client.close(); } } main().catch(console.error);

This code connects to a MongoDB server running on the default port, 27017, on your local machine. If you run this script using node index.js, you should see the message "Connected to MongoDB" in your terminal.

Creating a Document

In MongoDB, data is stored in documents, which are JSON-like objects containing key-value pairs. To create a new document, we will be working with the insertOne() method, which inserts a single document into a collection.

Let's start by creating a new collection named "users" and insert a document into it. Modify your index.js file with the following code:

const { MongoClient } = require('mongodb'); async function main() { const uri = 'mongodb://localhost:27017'; const client = new MongoClient(uri, { useUnifiedTopology: true }); try { await client.connect(); const db = client.db('myDatabase'); const usersCollection = db.collection('users'); const user = { name: 'John Doe', age: 30, email: '[email protected]', }; const result = await usersCollection.insertOne(user); console.log('User created with ID:', result.insertedId); } catch (error) { console.error('Error connecting to MongoDB:', error); } finally { await client.close(); } } main().catch(console.error);

Run the scriptusing node index.js, and you should see a message like "User created with ID: some_id" in your terminal, where some_id is the auto-generated unique identifier for the newly created document.

Reading Documents

Once you have data in your MongoDB database, you'll want to retrieve and display it. You can do this using the find() and findOne() methods, which allow you to query the database and return matching documents.

Reading a Single Document

To read a single document from a collection, use the findOne() method. It accepts a query object as an argument and returns the first document that matches the query. Update your index.js file with the following code to find a user by their email address:

const { MongoClient } = require('mongodb'); async function main() { const uri = 'mongodb://localhost:27017'; const client = new MongoClient(uri, { useUnifiedTopology: true }); try { await client.connect(); const db = client.db('myDatabase'); const usersCollection = db.collection('users'); const query = { email: '[email protected]' }; const user = await usersCollection.findOne(query); console.log('User found:', user); } catch (error) { console.error('Error connecting to MongoDB:', error); } finally { await client.close(); } } main().catch(console.error);

Reading Multiple Documents

To read multiple documents from a collection, use the find() method. It accepts a query object as an argument and returns a cursor that you can use to iterate through the matching documents. Update your index.js file with the following code to find all users with the name "John Doe":

const { MongoClient } = require('mongodb'); async function main() { const uri = 'mongodb://localhost:27017'; const client = new MongoClient(uri, { useUnifiedTopology: true }); try { await client.connect(); const db = client.db('myDatabase'); const usersCollection = db.collection('users'); const query = { name: 'John Doe' }; const cursor = usersCollection.find(query); const users = await cursor.toArray(); console.log('Users found:', users); } catch (error) { console.error('Error connecting to MongoDB:', error); } finally { await client.close(); } } main().catch(console.error);

Updating Documents

You can update documents in MongoDB using the updateOne() and updateMany() methods. These methods accept a query object to select the documents to update and an update object to specify the modifications.

Updating a Single Document

To update a single document, use the updateOne() method. Update your index.js file with the following code to change the email address of a user:

const { MongoClient } = require('mongodb'); async function main() { const uri = 'mongodb://localhost:27017'; const client = new MongoClient(uri, { useUnifiedTopology: true }); try { await client.connect(); const db = client.db('myDatabase'); const usersCollection = db.collection('users'); const query = { email: '[email protected]' }; const update = { $set: { email: '[email protected]' } }; const result = await usersCollection.updateOne(query, update); console.log('User updated:', result.modifiedCount); } catch (error) { console.error('Error connecting to MongoDB:', error); } finally { await client.close(); } } main().catch(console.error);

Updating MultipleDocuments

To update multiple documents, use the updateMany() method. Update your index.js file with the following code to increment the age of all users with the name "John Doe" by 1:

const { MongoClient } = require('mongodb'); async function main() { const uri = 'mongodb://localhost:27017'; const client = new MongoClient(uri, { useUnifiedTopology: true }); try { await client.connect(); const db = client.db('myDatabase'); const usersCollection = db.collection('users'); const query = { name: 'John Doe' }; const update = { $inc: { age: 1 } }; const result = await usersCollection.updateMany(query, update); console.log('Users updated:', result.modifiedCount); } catch (error) { console.error('Error connecting to MongoDB:', error); } finally { await client.close(); } } main().catch(console.error);

Deleting Documents

You can delete documents in MongoDB using the deleteOne() and deleteMany() methods. These methods accept a query object to select the documents to delete.

Deleting a Single Document

To delete a single document, use the deleteOne() method. Update your index.js file with the following code to delete a user by their email address:

const { MongoClient } = require('mongodb'); async function main() { const uri = 'mongodb://localhost:27017'; const client = new MongoClient(uri, { useUnifiedTopology: true }); try { await client.connect(); const db = client.db('myDatabase'); const usersCollection = db.collection('users'); const query = { email: '[email protected]' }; const result = await usersCollection.deleteOne(query); console.log('User deleted:', result.deletedCount); } catch (error) { console.error('Error connecting to MongoDB:', error); } finally { await client.close(); } } main().catch(console.error);

Deleting Multiple Documents

To delete multiple documents, use the deleteMany() method. Update your index.js file with the following code to delete all users with the name "John Doe":

const { MongoClient } = require('mongodb'); async function main() { const uri = 'mongodb://localhost:27017'; const client = new MongoClient(uri, { useUnifiedTopology: true }); try { await client.connect(); const db = client.db('myDatabase'); const usersCollection = db.collection('users'); const query = { name: 'John Doe' }; const result = await usersCollection.deleteMany(query); console.log('Users deleted:', result.deletedCount); } catch (error) { console.error('Error connecting to MongoDB:', error); } finally { await client.close(); } } main().catch(console.error);

FAQ

1. What are the differences between MongoDB and traditional relational databases?

MongoDB is a NoSQL database that uses a document-oriented model for data storage, while traditional relational databases use a table-based model. MongoDB provides more flexibility and scalability compared to relational databases, as it allows for storing complex data structures like arrays and nested objects.

2. How do I create an index in MongoDB?

To create an index in MongoDB, use the createIndex() method on a collection. For example, to create an index on the "email" field of the "users" collection, use the following code:

await usersCollection.createIndex({ email: 1 });

3. Can I use transactions in MongoDB?

Yes, MongoDB supports multi-document transactions starting from version 4.0 for replica sets and version 4.2 for sharded clusters. Transactions allow you to perform multiple read and write operations atomically, ensuring data consistency.

Here's an example of using a transaction to transfer funds between two bank accounts:

const { MongoClient } = require('mongodb'); async function main() { const uri = 'mongodb://localhost:27017'; const client = new MongoClient(uri, { useUnifiedTopology: true }); try { await client.connect(); const session = client.startSession(); const db = client.db('myDatabase'); const accountsCollection = db.collection('accounts'); const fromAccountId = 'account1'; const toAccountId = 'account2'; const transferAmount = 100; try { session.startTransaction(); await accountsCollection.updateOne( { _id: fromAccountId, balance: { $gte: transferAmount } }, { $inc: { balance: -transferAmount } }, { session } ); await accountsCollection.updateOne( { _id: toAccountId }, { $inc: { balance: transferAmount } }, { session } ); await session.commitTransaction(); console.log('Transaction committed'); } catch (error) { await session.abortTransaction(); console.error('Transaction aborted:', error); } finally { session.endSession(); } } catch (error) { console.error('Error connecting to MongoDB:', error); } finally { await client.close(); } } main().catch(console.error);

This code first starts a new transaction with startSession() and then performs two updateOne() operations to transfer funds between the accounts. If the operations are successful, the transaction is committed with commitTransaction(). If an error occurs, the transaction is aborted with abortTransaction().

Conclusion

In this tutorial, we have covered the basics of MongoDB CRUD operations, including creating, reading, updating, and deleting documents. By understanding these fundamental operations, you are now equipped to build powerful and scalable applications using MongoDB as your data storage solution.

Sharing is caring

Did you like what Mehul Mohan wrote? Thank them for their work by sharing it on social media.

0/10000

No comments so far