How To Use MongoDB CRUD Operations

by | MongoDB

Introduction to MongoDB and CRUD Operations

Introduction

MongoDB is a powerful, flexible NoSQL database that allows for efficient storage and retrieval of data in a document-oriented format. This guide will provide you with clear and practical instructions on performing CRUD (Create, Read, Update, Delete) operations in MongoDB.

Setting Up MongoDB

Here are the steps to set up MongoDB:

  1. Download MongoDB: Visit the official MongoDB website and download the community server version compatible with your operating system.
  2. Install MongoDB: Follow the installation instructions for your specific OS.
  3. Run MongoDB: Start the MongoDB server by running mongod from your command line. You may need to use the full path to the mongod executable, or ensure it's in your system's PATH.

Using MongoDB Shell

MongoDB comes with an interactive shell called mongo, which can be used to execute database commands. Once your server is running, open a new terminal and type mongo to start the shell.

CRUD Operations in MongoDB

Create

To insert a document into a collection, use the insertOne() or insertMany() method.

// Insert a single document
db.collection_name.insertOne({ key: "value", key2: "value2" });

// Insert multiple documents
db.collection_name.insertMany([
    { key: "value1", key2: "value2" },
    { key: "value3", key2: "value4" }
]);

Read

To retrieve documents from a collection, use the find() method. You can apply conditions to match specific documents.

// Retrieve all documents
db.collection_name.find({});

// Retrieve documents with specific criteria
db.collection_name.find({ key: "value" });

Update

To update existing documents in a collection, use the updateOne(), updateMany(), or replaceOne() method.

// Update a single document
db.collection_name.updateOne(
    { key: "value" }, // filter
    { $set: { key2: "new_value2" } } // update
);

// Update multiple documents
db.collection_name.updateMany(
    { key: "value" }, // filter
    { $set: { key2: "new_value2" } } // update
);

// Replace a document
db.collection_name.replaceOne(
    { key: "value" }, // filter
    { key: "new_value", key2: "new_value2" } // new document
);

Delete

To remove documents from a collection, use the deleteOne() or deleteMany() method.

// Delete a single document
db.collection_name.deleteOne({ key: "value" });

// Delete multiple documents
db.collection_name.deleteMany({ key: "value" });

Summary

This guide has introduced you to basic CRUD operations in MongoDB. You have learned how to create, read, update, and delete documents in a MongoDB collection. The commands provided can be executed directly in the MongoDB shell to manage your data efficiently.

Setting Up Your MongoDB Environment

1. Configuring MongoDB

After installing MongoDB (assuming installation steps have been covered in previous sections), you can configure it by editing the mongod.conf file. This file typically resides in /etc/mongod.conf on Linux or C:\Program Files\MongoDB\Server\<version>\bin\mongod.cfg on Windows.

Below are essential configurations:

# mongod.conf

# Network interfaces
net:
  port: 27017
  bindIp: 127.0.0.1  # Listen only on localhost. Change to 0.0.0.0 to listen on all IPs.

# Data storage
storage:
  dbPath: /var/lib/mongodb  # Path where MongoDB will store its data files
  journal:
    enabled: true  # Enable journaling for write ahead logs.

# Where and how to log messages
systemLog:
  destination: file
  logAppend: true
  path: /var/log/mongodb/mongod.log

# Process management options
processManagement:
  fork: true  # Run mongod as daemon (Linux)

# Security
security:
  authorization: enabled  # Enable authorization to enforce access control

2. Starting MongoDB

To start MongoDB, use the following command. Ensure the configuration file path is correct based on your OS:

# Linux
sudo service mongod start

# or using the configuration file directly
sudo mongod --config /etc/mongod.conf

# Windows
net start MongoDB

3. Connecting to MongoDB

To interact with MongoDB, use the mongo shell. Open a terminal and type:

mongo

You will get a prompt that looks like >, where you can start executing MongoDB commands.

4. Creating a Database and Collection

Once connected to the MongoDB shell, use the following commands to create a database and a collection:

# Switch to your database. This will create the database if it does not exist.
use myDatabase

# Create a collection named 'myCollection'
db.createCollection('myCollection')

5. Inserting Documents

Insert a sample document into myCollection:

db.myCollection.insertOne(
  {
    name: 'John Doe',
    age: 30,
    address: {
      street: '123 Main St',
      city: 'Anytown',
      state: 'CA',
      zip: '12345'
    }
  }
)

6. Querying Documents

Fetch all documents from the collection:

db.myCollection.find()

Fetch documents with specific criteria:

db.myCollection.find({ age: { $gte: 18 } })

7. Updating Documents

Update a single document in myCollection:

db.myCollection.updateOne(
  { name: 'John Doe' },  // Query
  { $set: { age: 31 } }  // Update operation
)

8. Deleting Documents

Delete a single document from myCollection:

db.myCollection.deleteOne({ name: 'John Doe' })

9. Security Configuration

To secure your MongoDB deployment, create an administrative user and enable authentication:

# Switch to admin database
use admin

# Create admin user
db.createUser(
  {
    user: 'admin',
    pwd: 'securepassword123',
    roles: [ { role: 'userAdminAnyDatabase', db: 'admin' } ]
  }
)

After creating the admin user, you must restart MongoDB and use authentication in all future connections:

# Restart MongoDB to enable authentication
sudo service mongod restart

# Connect with authentication
mongo -u "admin" -p "securepassword123" --authenticationDatabase "admin"

In your application's connection string, include the username and password for secure connections:

mongodb://admin:securepassword123@localhost:27017/myDatabase

With this setup, you've completed configuring and securely connecting to MongoDB for CRUD operations.

MongoDB Create Operations: Adding Data

This section covers how to perform Create operations (adding data) in MongoDB. We will demonstrate these operations using MongoDB shell commands.

Inserting a Single Document

Example

use myDatabase
db.myCollection.insertOne({
    name: "John Doe",
    age: 30,
    email: "johndoe@example.com",
    address: {
        street: "123 Main St",
        city: "Springfield",
        zip: "12345"
    }
})

Inserting Multiple Documents

Example

db.myCollection.insertMany([
    {
        name: "Jane Smith",
        age: 25,
        email: "janesmith@example.com",
        address: {
            street: "456 Oak St",
            city: "Metropolis",
            zip: "67890"
        }
    },
    {
        name: "Adam Johnson",
        age: 35,
        email: "adamjohnson@example.com",
        address: {
            street: "789 Pine St",
            city: "Gotham",
            zip: "11223"
        }
    }
])

Verifying Inserted Documents

Example

To verify that documents have been inserted correctly, use the find command:

db.myCollection.find().pretty()

This command will list all the documents in the myCollection collection in a readable format.


By executing these commands in your MongoDB shell, you can successfully add data to your MongoDB collections.

Retrieving Data from MongoDB

In this section, we will focus on how to perform read operations to retrieve data from a MongoDB database. The common methods for reading data from MongoDB include find, findOne, and using query operators to filter the results.

Establishing a Connection

Ensure you have already established a connection to your MongoDB instance. Here's a generic representation assuming some connection is already in place:

const { MongoClient } = require('mongodb');
const uri = "your_mongodb_uri";
const client = new MongoClient(uri);

await client.connect();
const database = client.db('your_database');
const collection = database.collection('your_collection');

Using find Method

find is used to retrieve multiple documents that match the specified query criteria.

Example: Retrieve All Documents

const cursor = collection.find({});
const results = await cursor.toArray();

console.log(results); // Logs all documents in the collection

Example: Retrieve Documents with a Query

Search documents where the field status is active.

const query = { status: 'active' };
const cursor = collection.find(query);
const results = await cursor.toArray();

console.log(results); // Logs documents where status is 'active'

Advanced Query with Projection and Sorting

Retrieve documents, but only include specific fields, and sort them.

const query = { status: 'active' };
const projection = { name: 1, status: 1 };
const options = {
  projection: projection,
  sort: { name: 1 }
};

const cursor = collection.find(query, options);
const results = await cursor.toArray();

console.log(results); // Logs documents with 'name' and 'status' fields, sorted by 'name'

Using findOne Method

findOne is used to retrieve a single document that matches the specified query criteria.

Example: Retrieve Single Document

const query = { _id: 'specific_id_value' };
const result = await collection.findOne(query);

console.log(result); // Logs the first document found with the specified _id

Example: Find Single Document with Projection

Retrieve a single document but project only specific fields.

const query = { status: 'pending' };
const projection = { name: 1, status: 1 };

const result = await collection.findOne(query, { projection });

console.log(result); // Logs the document with 'name' and 'status' fields

Query Operators

MongoDB supports various query operators to facilitate complex query conditions.

Example: Using $gt and $lt Operators

Retrieve documents where a numeric field age is greater than 25 and less than 40.

const query = { age: { $gt: 25, $lt: 40 } };
const cursor = collection.find(query);
const results = await cursor.toArray();

console.log(results); // Logs documents where age is between 26 and 39

Example: Using $in Operator

Retrieve documents where the field category equals either A or B.

const query = { category: { $in: ['A', 'B'] } };
const cursor = collection.find(query);
const results = await cursor.toArray();

console.log(results); // Logs documents where category is 'A' or 'B'

Closing the Connection

After completing your read operations, always close the database connection.

await client.close();

Conclusion

This section covered several methods to read data from a MongoDB database, leveraging various query capabilities, projection, and sorting options. Implement these examples to effectively retrieve and manipulate the data as required.

Update Operations: Modifying Existing Data in MongoDB

Introduction

Updating documents in MongoDB is crucial for maintaining the relevance and accuracy of your database. This module will walk you through various methods to modify existing data in MongoDB.

Basic Update Operations

MongoDB provides several methods to update documents within a collection. These include updateOne, updateMany, and findOneAndUpdate.

updateOne

This operation updates a single document that matches a filter.

Syntax:

db.collection.updateOne(
   <filter>,
   <update>,
   <options>
)

Example:

db.students.updateOne(
   { "student_id": 101 },
   { $set: { "grade": "A" } }
)

updateMany

This operation updates multiple documents that match a filter.

Syntax:

db.collection.updateMany(
   <filter>,
   <update>,
   <options>
)

Example:

db.students.updateMany(
   { "grade": "B" },
   { $set: { "grade": "B+" } }
)

Update Operators

MongoDB provides various operators to update the document fields.

$set

Sets the value of a field in a document.

Example:

db.students.updateOne(
   { "student_id": 102 },
   { $set: { "email": "new_email@example.com" } }
)

$inc

Increments the value of a field by a specified amount.

Example:

db.students.updateOne(
   { "student_id": 103 },
   { $inc: { "attendance": 1 } }
)

$unset

Removes the specified field from a document.

Example:

db.students.updateOne(
   { "student_id": 104 },
   { $unset: { "middle_name": "" } }
)

Upsert Operation

If you want to update an existing document or insert a new document if no match is found, use the upsert option.

Example:

db.students.updateOne(
   { "student_id": 105 },
   { $set: { "name": "John Doe", "grade": "B" } },
   { upsert: true }
)

Array Update Operators

MongoDB provides operators to update fields that are arrays.

$push

Adds an element to an array.

Example:

db.students.updateOne(
   { "student_id": 106 },
   { $push: { "courses": "Math" } }
)

$pull

Removes an element from an array.

Example:

db.students.updateOne(
   { "student_id": 107 },
   { $pull: { "courses": "History" } }
)

$addToSet

Adds an element to an array only if it does not exist.

Example:

db.students.updateOne(
   { "student_id": 108 },
   { $addToSet: { "courses": "Science" } }
)

Conclusion

By using these various update operations and operators, you can effectively manage and modify your MongoDB data to keep it accurate and up-to-date. Ensure to choose the right operator and method based on the context and requirements of your application.

Delete Operations: Removing Data from MongoDB

In this section, you'll learn how to perform delete operations in MongoDB, enabling you to remove data from your collections effectively. We'll look at two key methods of deleting documents: deleteOne and deleteMany.

deleteOne()

The deleteOne method removes a single document that matches the specified filter. If multiple documents match the filter, only the first match will be deleted.

Syntax

db.collection.deleteOne(
   <filter>,
   <options>
)
  • filter: The selection criteria for the deletion.
  • options: (Optional) Additional options to control the deletion operation.

Example

Suppose you have a collection called students and you want to delete a student with the name "John Doe":

db.students.deleteOne({ name: "John Doe" });

This query will delete the first document found with the name "John Doe".

deleteMany()

The deleteMany method removes all documents that match the specified filter.

Syntax

db.collection.deleteMany(
   <filter>,
   <options>
)
  • filter: The selection criteria for the deletion.
  • options: (Optional) Additional options to control the deletion operation.

Example

Suppose you want to delete all students who have not registered for the new semester in the students collection:

db.students.deleteMany({ registeredForNewSemester: false });

This query will delete all documents where registeredForNewSemester is false.

Options

Both deleteOne and deleteMany methods have an optional writeConcern parameter, which allows you to control the acknowledgment of the write operation. This can be useful for ensuring data integrity during delete operations.

Example with writeConcern

db.students.deleteMany(
   { registeredForNewSemester: false },
   { writeConcern: { w: "majority", wtimeout: 5000 } }
);

This ensures that the delete operation is acknowledged by the majority of the nodes in the replica set, with a timeout of 5000 milliseconds.

Conclusion

Deleting documents in MongoDB is straightforward with the deleteOne and deleteMany methods. These methods provide flexibility in removing single or multiple documents based on specified criteria. Always ensure to use appropriate filters to avoid unintentional data loss.

Related Posts