A Guide to CRUD Operations with MongoDB

Posted By :Vikrant Kumar |10th October 2023

Title: A Guide to CRUD Operations with MongoDB

 

Introduction

 

MongoDB is a popular NoSQL database that stores data in a flexible, JSON-like format called BSON (Binary JSON). One of the fundamental operations when working with databases is CRUD, which stands for Create, Read, Update, and Delete. In this blog post, we'll explore how to perform CRUD operations with MongoDB, using both the MongoDB shell and Node.js.

 

Prerequisites

 

Before we dive into CRUD operations, make sure you have MongoDB installed and running on your system. You can download it from the official website (https://www.mongodb.com/try/download/community) and follow the installation instructions.

 

CRUD Operations in MongoDB

 

1. Create (Insert)

The Create operation in MongoDB involves inserting new documents into a collection. A collection is similar to a table in relational databases. To insert a document, use the `insertOne()` or `insertMany()` method.

 

  Javascript

   // Insert a single document

  db.collectionName.insertOne({ key1: value1, key2: value2 });

 

  // Insert multiple documents

  db.collectionName.insertMany([

    { key1: value1, key2: value2 },

    { key1: value3, key2: value4 },

  ]);

 

 

2. Read (Query)

  The Read operation retrieves documents from a collection. MongoDB provides various methods for querying data:

 

  - `find()`: Retrieve all documents or specify query criteria.

  - `findOne()`: Retrieve a single document.

  - Query operators (e.g., `$eq`, `$gt`, `$lt`, `$in`) allow for complex queries.

 

  // Find all in a collection

  db.collectionName.find();

 

  // Find documents matching a specific condition

  db.collectionName.find({ key1: value1 });

 

  // Update a single document

  db.collectionName.findOne({ key2: value2 });

 

 

3. Update

 

  Updating documents in MongoDB is done using the `updateOne()` and `updateMany()` methods. You specify a filter to identify the document(s) to update and use the `$set` operator to specify the changes.

 

  // Update a single document

  db.collectionName.updateOne({ key1: value1 }, { $set: { key2: newValue } });

 

  // Update multiple documents

  db.collectionName.updateMany({ key1: value1 }, { $set: { key2: newValue } });

 

 

4. Delete

  The Delete operation removes documents from a collection. You can use the `deleteOne()` and `deleteMany()` methods to delete documents based on a filter.

 

  // Delete a single document

  db.collectionName.deleteOne({ key1: value1 });

 

  // Delete multiple documents

  db.collectionName.deleteMany({ key1: value1 });

 

Node.js and MongoDB

 

Now, let's see how to perform CRUD operations using Node.js and the MongoDB Node.js driver.

 

1. Connecting to MongoDB

 

  To connect to MongoDB from a Node.js application, you'll need the `mongodb` driver. You can install it using npm or yarn:

 

  npm install mongodb

 

 

  Here's an example of connecting to MongoDB:

 

  const MongoClient = require('mongodb').MongoClient;

  const uri = 'mongodb://localhost:27017/mydb'; // Replace with your MongoDB connection string

 

  MongoClient.connect(uri, (err, client) => {

    if (err) throw err;

    const db = client.db('mydb');

    // Perform CRUD operations here

    client.close();

  });

 

2. Performing CRUD Operations

 

  Now that you're connected to MongoDB, you can perform CRUD operations as follows:

 

  - Create: Use the `insertOne()` or `insertMany()` methods.

  - Read: Use the `find()` or `findOne()` methods.

  - Update: Use the `updateOne()` or `updateMany()` methods.

  - Delete: Use the `deleteOne()` or `deleteMany()` methods.

 

  Here's an example of inserting a document:

 

  const newDocument = { name: 'John', age: 30 };

  db.collection('mycollection').insertOne(newDocument, (err, result) => {

    if (err) throw err;

    console.log('Document inserted');

  });

 

  And reading documents:

 

  db.collection('mycollection').find({ age: { $gt: 25 } }).toArray((err, documents) => {

    if (err) throw err;

    console.log(documents);

  });

 

Conclusion

 

CRUD operations are fundamental when working with databases, and MongoDB makes it easy to perform them using either the MongoDB shell or Node.js. Whether you're building a small application or a large-scale system, MongoDB's flexibility and scalability make it a great choice for managing your data. Start exploring MongoDB's CRUD operations and build powerful applications today!


About Author

Vikrant Kumar

Vikrant is a skilled and knowledgeable back-end developer with extensive experience in the industry. He is proficient in various programming languages, such as NodeJS, ExpressJS, MongoDB, React, Angular, and JavaScript. Vikrant has worked on several challenging projects, including Konfer, and has a deep understanding of development principles. He is committed to expanding his knowledge of new technologies and constantly improving his skills to deliver exceptional software products.

Request For Proposal

[contact-form-7 404 "Not Found"]

Ready to innovate ? Let's get in touch

Chat With Us