Join our Discord Server
Ajeet Raina Ajeet Singh Raina is a former Docker Captain, Community Leader and Distinguished Arm Ambassador. He is a founder of Collabnix blogging site and has authored more than 700+ blogs on Docker, Kubernetes and Cloud-Native Technology. He runs a community Slack of 9800+ members and discord server close to 2600+ members. You can follow him on Twitter(@ajeetsraina).

Performing CRUD operations in Mongo using Python and Docker

4 min read

MongoDB is a popular open-source document-oriented NoSQL database that uses a JSON-like document model with optional schemas. It was first released in 2009 and has since become widely used in both small and large-scale applications.

MongoDB is popular because it offers a flexible data model, making it easy to store and manage a wide variety of data types, including structured, semi-structured, and unstructured data. It can also scale horizontally by adding more servers to a cluster, making it well-suited for large-scale applications.

In terms of popularity, MongoDB is one of the most widely used NoSQL databases. According to the DB-Engines ranking, which measures database popularity based on various factors, MongoDB is currently ranked as the fourth most popular database system overall, after Oracle, MySQL, and PostgreSQL. It is also ranked as the most popular NoSQL database. Many popular websites and services use MongoDB, including Forbes, eBay, and The Weather Channel.

A Developer Data Platform

Mongo is a document-oriented NoSQL database program that is commonly used by developers to store and manage data. While it is primarily a database technology, it can be considered as part of a larger developer data platform.

MongoDB is often used as part of a technology stack that includes other developer tools such as programming languages, web servers, and application frameworks. In this context, it is one component of a larger platform that developers use to build and manage applications.

In addition to providing a database for storing data, MongoDB also includes features for data retrieval, indexing, and querying. It has become popular for building applications that require flexible data models, real-time analytics, and high availability.

Therefore, while MongoDB is not a complete developer data platform by itself, it can be an important component of one, particularly for developers building applications that require flexible data storage and retrieval capabilities.

Getting Started

Performing CRUD (Create, Read, Update, Delete) operations in MongoDB using Docker involves a few steps:

Step 1. Install Docker

If you haven’t already, you’ll need to install Docker on your machine. You can download and install Docker from the official website for your platform.

Step 2. Pull MongoDB Image

You need to pull the MongoDB image from the Docker Hub repository using the following command:

docker pull mongo

Step 3. Run MongoDB Container

You need to run the MongoDB container by using the following command:

docker run -d -p 27017:27017 --name mongodb mongo

This command will start a new container named “mongodb” and map the container’s port 27017 to the host’s port 27017. The “-d” option runs the container in detached mode, which means the container will run in the background.

Step 4. Connect to MongoDB

To connect to the MongoDB container, you need to open a new terminal window and run the following command:

docker exec -it mongodb bash

This command will start a new shell in the “mongodb” container, allowing you to run commands inside the container.

Step 5. Use MongoDB Shell

Once you’re connected to the MongoDB container, you can use the MongoDB shell to perform CRUD operations. The MongoDB shell is a JavaScript shell that allows you to interact with the database. You can start the MongoDB shell by running the following command:

mongo

This command will start the MongoDB shell and connect to the default database.

Performing Mongo CRUD Operations

Once you’re in the MongoDB shell, you can perform CRUD operations using the following commands:

Creating a Document

To create a new document in a collection, use the insertOne() method. For example:

db.users.insertOne({name: "John", age: 25})

To create a document in MongoDB using Python, you will need to install the pymongo library, which is the official Python driver for MongoDB. You can install it using pip by running the command:

pip install pymongo

Assuming you already have a MongoDB instance running and have the necessary permissions, you can use the following Python script to create a document in a collection:

import pymongo

# Connect to the MongoDB instance
client = pymongo.MongoClient("mongodb://localhost:27017/")

# Select the database and collection you want to use
db = client["mydatabase"]
collection = db["mycollection"]

# Define the document you want to insert
document = {
  "name": "John",
  "age": 30,
  "city": "New York"
}

# Insert the document into the collection
result = collection.insert_one(document)

# Print the ID of the inserted document
print(result.inserted_id)

In this example, the script connects to a MongoDB instance running on the local machine and selects a database called “mydatabase” and a collection called “mycollection”. It then defines a document as a Python dictionary and inserts it into the collection using the insert_one() method. The script finally prints the ID of the inserted document.

You can modify this script to suit your specific needs, such as changing the database and collection names, or adding more fields to the document.

Reading the Document

Assuming you already have a MongoDB instance running and have the necessary permissions, you can use the following Python script to read a document from a collection:

import pymongo

# Connect to the MongoDB instance
client = pymongo.MongoClient("mongodb://localhost:27017/")

# Select the database and collection you want to use
db = client["mydatabase"]
collection = db["mycollection"]

# Find a document in the collection
document = collection.find_one({"name": "John"})

# Print the document
print(document)

In this example, the script connects to a MongoDB instance running on the local machine and selects a database called “mydatabase” and a collection called “mycollection”. It then uses the find_one() method to retrieve a document from the collection with the name “John”. The script finally prints the document.

You can modify this script to suit your specific needs, such as changing the database and collection names, or using different search criteria to find a document.

Updating the Document

To update an existing document in a collection, use the updateOne() method. For example:

db.users.updateOne({name: "John"}, {$set: {age: 30}})

Assuming you already have a MongoDB instance running and have the necessary permissions, you can use the following Python script to update a document in a collection:

import pymongo

# Connect to the MongoDB instance
client = pymongo.MongoClient("mongodb://localhost:27017/")

# Select the database and collection you want to use
db = client["mydatabase"]
collection = db["mycollection"]

# Find the document you want to update
query = {"name": "John"}
new_values = {"$set": {"age": 31}}

# Update the document
result = collection.update_one(query, new_values)

# Print the number of documents updated
print(result.modified_count)

In this example, the script connects to a MongoDB instance running on the local machine and selects a database called “mydatabase” and a collection called “mycollection”. It then uses the update_one() method to update a document in the collection with the name “John”. The $set operator is used to modify the “age” field of the document to 31.

The update_one() method returns a UpdateResult object, which contains information about the update operation, including the number of documents updated. The script finally prints the number of documents updated.

Deleting the Document

Assuming you already have a MongoDB instance running and have the necessary permissions, you can use the following Python script to delete a document from a collection:

import pymongo

# Connect to the MongoDB instance
client = pymongo.MongoClient("mongodb://localhost:27017/")

# Select the database and collection you want to use
db = client["mydatabase"]
collection = db["mycollection"]

# Find the document you want to delete
query = {"name": "John"}

# Delete the document
result = collection.delete_one(query)

# Print the number of documents deleted
print(result.deleted_count)

In this example, the script connects to a MongoDB instance running on the local machine and selects a database called “mydatabase” and a collection called “mycollection”. It then uses the delete_one() method to delete a document from the collection with the name “John”.

The delete_one() method returns a DeleteResult object, which contains information about the delete operation, including the number of documents deleted. The script finally prints the number of documents deleted.

You can modify this script to suit your specific needs, such as changing the database and collection names, or using different search criteria to delete a document or deleting multiple documents using the delete_many() method

Have Queries? Join https://launchpass.com/collabnix

Ajeet Raina Ajeet Singh Raina is a former Docker Captain, Community Leader and Distinguished Arm Ambassador. He is a founder of Collabnix blogging site and has authored more than 700+ blogs on Docker, Kubernetes and Cloud-Native Technology. He runs a community Slack of 9800+ members and discord server close to 2600+ members. You can follow him on Twitter(@ajeetsraina).
Join our Discord Server
Index