Python | CRUD operations in MongoDB

Today in this article, we will talk about some operations that can be performed on the database using the queries of MongoDB. In this article on CRUD operations in MongoDB with Python, we will learn how to perform the operations like Create, Read, Update, and Delete to manipulate the documents in the database. This time we will perform these operations using Python. Before performing those 4 basic operations, let us look at how to use and connect MongoDB with Python.

Installing pymongo

To access the MongoDB database and perform CRUD operations in MongoDB, Python needs a MongoDB driver. We’ll be using the “PyMongo” MongoDB driver in this article. Tools for dealing with the MongoDB database from Python are included in the PyMongo package. Python.exe must be present in your system’s PATH for the installer to succeed. Define Python in your system environment accordingly. Using the pip tool, you can install MongoDB Connector.

Enter the following command on the command prompt to install PyMongo:

pip install pymongo

Now that we have installed pymongo, the next step is to start our MongoDB Database Server

Starting MongoDB Database Server

This can simply be done by opening the Terminal and by typing “mongo

starting mongodb server

Importing pymongo and Establishing Connection

from pymongo import MongoClient
client = MongoClient("mongodb://localhost:27017")

Explanation:

Finally, we are starting with the CRUD operations in MongoDB. First, we need to import our installed library. This can be done by the first line written above. Now to establish the connection with MongoDB, we need to enter the Connection URI. This URI can be found when you open your MongoDB Compass. This URL needs to be passed to the MongoClient.

CRUD operations in MongoDB with Python

Connecting to Database and Retrieving Collection

database_name = "Customer"
db = client[database_name]

collection_name = "customer_info"
collection = db[collection_name]

Explanation:

Now that we have made our connection, it is time to make a database. To make a database we first declared a variable and entered the name of our database into it. Then, we passed that to the client variable that stores our connection. Once the database is connected, now we can access the collections in it or make collections. In the same way, we can make or access the collection by passing it to the variable that stores our database info.

NOTE: It must be kept in mind that we cannot see either the database or collection in MongoDB compass until and unless there is a document in it. So whenever we are creating a database or collection, it is necessary to at least insert one document to check whether our database and collection are created or not.

Finally, we will start with CRUD operations in MongoDB with Python.

C – Creating / Inserting documents

There are two methods for adding documents to a collection:

  1. Adding just one document to the collection.
  2. Adding a number of documents to the collection

Let us take a look at the below code:

collection.insert_many([{
    "contact": 8877665544,
    "item_purchased": "motorola",
    "name": "sam johnson",
    "country": "australia",
    "state": "new south wales",
    "store": "moto store - australia"
},
    {"contact": 1234512345,
     "item_purchased": "iphone",
     "name": "borris john",
     "state": "texas",
     "store": "ivenus - texas",
     "country": "america"
     },
    {
    "contact": 3245678412,

    "item_purchased": "micormax",
    "name": "harry berklin",
    "country": "australia",
    "state": "Queensland",
    "store": "micro store - australia"
},
    {
    "contact":  9898989898,
    "item_purchased": "samsung galaxy ",
    "name": "malella harison",
    "state": "karnataka",
    "store": "samsung - india",
    "country": "India"
},

])

Explanation:

  • insert_one() – This function is used to add a single document to a collection
  • insert_many() – This method is used to add numerous documents. In this instance, we’ve added a number of papers to the “customer_info” collection. Here, in the insert_many() function we use commas to divide up numerous items before passing them into the customer_info collection. Multiple items are being handed in when brackets are used between parentheses. A nested method is a common name for such a method.

State of Database before inserting 4 documents

database before data

State of Database after inserting 4 documents

database after data

R – Reading documents

This mode of operation simply refers to the accessing/reading of the documents that are stored in the database. R stands for read in CRUD operations in MongoDB or any other database.

These two methods can be used to get data.

  1. Obtaining one document
  2. Obtaining several papers

Using find_one() to read one document

from pymongo import MongoClient
client = MongoClient("mongodb://localhost:27017")

database_name = "Customer"
db = client[database_name]

collection_name = "customer_info"
collection = db[collection_name]

single_doc = collection.find_one()
print(single_doc)

Output:

output

Explanation:

find_one() method only provides the first document of a collection that meets the specified criteria.

Using find_many() to read one document

multiple_doc = collection.find()
 
for data in multiple_doc:
    print(data)

Output:

output

Explanation:

In MongoDB, if we want to access multiple documents then we use the find_many() function which is used to return the document or documents depending on the supplied criteria.

U – Updating documents

The following two methods can be used to update the documents.

  1. Changing just one document
  2. Changing several documents

Two arguments must be supplied to the function in order to update the documents. A filter parameter makes up the first parameter, while an update parameter makes up the second. The query that matches the revised document is the filter parameter. The update option specifies the changes that should be made to the document.

Using update_one() to read one document

from pymongo import MongoClient
client = MongoClient("mongodb://localhost:27017")

database_name = "Customer"
db = client[database_name]

collection_name = "customer_info"
collection = db[collection_name]

update_single = collection.update_one({"name": "sam johnson"}, {"$set":{ "contact": 1212}})

print(update_single)

Output before executing update_one() function:

output before update

Output after executing update_one() function:

output after update

Explanation:

We utilize the update_one() function to update a single document. Two arguments must be supplied to the procedure in order to update the documents. A filter parameter makes up the first parameter, while an update parameter makes up the second. The query that matches the revised document is the filter parameter. The update option specifies the changes that should be made to the document. The value for the fields we want to change will be provided using the “$set” key in the following step. The update will be applied if the specified filter matches the already-existing record.

Using update_many() to read many documents

update_multiple = collection.update_many({"country": "australia"}, {"$set":{ "country": "AUS"}})

print(update_multiple)

Output:

output

Explanation:

Here in the above query, we used the update_many() function that helps us in updating multiple documents in one go. Here we selected all the documents that have the country Australia and then using the $set, we updated it with the value AUS.

D – Deleting documents

D stands for delete in CRUD operations in MongoDB or any other database. Moving on to the last operation in our article on CRUD operations in Python MongoDB. Deleting simply refers to removing the documents from the MongoDB database. The following two methods can be used to delete documents.

  1. Removing a single document
  2. Eliminating several documents

Removing a single document using the delete_one() function

from pymongo import MongoClient
client = MongoClient("mongodb://localhost:27017")

database_name = "Customer"
db = client[database_name]

collection_name = "customer_info"
collection = db[collection_name]

delete_single = collection.delete_one({ "contact": 1212})
print(delete_single)

Output before deleting a single document

data before delete

Output before deleting multiple documents

data after delete

Explanation:

Like the update and create operations, the delete operation only affects a single collection. Additionally, deletions of a single document are atomic. The documents you wish to delete from a collection can be defined using filters and criteria when performing delete actions. The criteria and filters function similarly to the filter options in Python’s read-only CRUD operations in MongoDB. One document can be eliminated from a MongoDB collection using the delete_one() function. Filters identify the document that will be removed. Only records that match the chosen filter are eliminated.

Removing multiple documents using the delete_many() function

delete_multiple = collection.update_many({"country": "australia"}, {"$set":{ "country": "AUS"}})

print(delete_single)

Output:

output

Explanation:

This function is used to delete multiple documents, based on the condition passed in the function, the value is matched and corresponding documents are deleted. We must always be careful whenever using the delete_many() function, as multiple documents get deleted. Here 2 documents got deleted as after the update operation we had two docs that had “AUS” as the country name.

Dropping a collection

To drop an entire collection in one go, we can simply use the drop() function. Executing this will delete all the documents that are stored in that particular document and the user will not be able to retrieve those documents.

collection.drop()

Required Files

Conclusion

Here is the end of our article on CRUD operations in MongoDB with Python, we learned about some functions that we can use to perform CRUD operations. I tried my best to explain the connection process the easiest way possible. We hope this article turns out to be a great source of learning for you. We will soon be back with another article till then keep Learning, Execting, and Building.


Also Read:

Share:

Author: Ayush Purawr