Integration of MongoDB into Python application

Godlin Hilda J
featurepreneur
Published in
4 min readMay 14, 2021

In this article, we are going to see how to integrate MongoDB as well as learn some basic commands that will help you get started.

We will be working with MongoDB Atlas so before starting make sure you have a collection in MongoDB Atlas. If not, refer to the below article

After you have done setting up, we will now integrate MongoDB into our Python application.

We gonna use a module called Pymongo to access MongoDB from our application. We first have to install this module. For that, we use the below command

$ pip install pymongo

Now we should import the module that we just downloaded and connect our collection.

Let’s understand the code

  • Line 1 — We are importing the Pymongo module
  • Line 3 — We are passing in our MONGO_URI to MongoClient class
  • Line 4 — Using the object that was created in line 3, we are accessing our database
  • Line 5 — Finally we are now accessing our collection that is present within our database

And we are done. All it takes are these 4 lines of code to integrate MongoDB into our application.

Basic CRUD commands of MongoDB :

Now that we have finished setting up, we will look at some basic commands to interact with our new setup DB

In MongoDB, every entry is called as post. These posts are in the form of dictionary containing many key-value pairs.

1. Insert

In order to insert data into our DB, we use one of the two methods insert_one or insert_many

  • As the name speaks for itself, insert_one is used to add one post
  • insert_many is used to insert more than one posts
# insert_one entry_1 ={"_id" : 1, "fruit" : "mango"} 
collection.insert_one(entry_1)

As already mentioned, Posts are in the form of key-value pairs. We can uniquely identify an entry using _id key. We can manually set the _id as we have done in the above snippet or if we don’t specify _id, MongoDB will automatically create an id for each post/entry. Here, collection is the object of our collection that we created while integrating MongoDB in the first section of the article.

# insert_manyentry_1 ={"_id" : 1, "fruit" : "mango"}
entry_2 ={"_id" : 2, "fruit" : "apple"}
collection.insert_many([entry_1,entry_2])

We can insert multiple entries by passing them as a list to the insert_many method.

2. Read

If we wanna read data from our collection, we should use find method. For getting a specific post from DB, we have written a query.

# syntax : collection.find({QUERY})results = collection.find({"fruit" : "apple"})
print(results)

Here, we are searching for an entry that contains fruit as apple . When we try to print results , we will get what is called as Cursor Object. Now, if we gonna access the value, we can iterate through results

for result in results:
print(result['fruit']) # prints "apple"
print(result['_id']) # prints 2

If we have more than one entry that satisfies the given query, then all of them will be returned. We can search by more than one field.

result = collection.find({"_id" : 1,"fruit" : "mango"})
# note here that each field is seperated by a comma

Sometimes, we would want to return all the posts in our DB. In that case, we don’t have to specify any query

results = collection.find() 

3. Delete

We are now moving on to delete the entries from our DB. The delete method is similar to find which we have just discussed.

# syntax : collection.delete_one({QUERY})
collection.delete({"_id" : 1}) # deletes the post with _id as 1

We can also use delete_many to delete multiple entries that fit our query.

collection.delete_many({"fruit" : "apple"})
# deletes all entries containing apple

If we want to delete all the entries in our DB, use the delete without passing any query.

collection.delete_many({}) # deletes all the entries

4.Update

In certain cases, we would want to update the value of entry rather than deleting it. For this we use update methods

  • If we want to update only one entry, we can use the update_one method.
  • If we want to update more the one entry, we can use the update_many method
# syntax : collection.update_one({QUERY},{"$set":{Key-value pair}})

The update method takes in two parameters the first one being the query. This query specifies which entry we want to change. Then we set the value using $set.

collection.update_one({"_id" : 1},{"$set" : {"fruit" : "kiwi"}})

After the above line is executed, the entry with _id-1 will no longer contain mango but will have kiwi.

We can also create new fields and set their value. For example, in our case we have only two fields per entry. Those are _id and fruit . Now say that we wanna add another field called color and set its value, we can use the update method to do the same.

collection.update_one({"_id" : 2},{"$set" : { "color" : "red"}})

After this execution, we will have our entry as follows

# Before 
{
"_id" : 2,
"fruit" : "apple"
}
# After
{
"_id" : 2,
"fruit" : "apple",
"color" : "red"
}

We have finally come to the end. Congratulations, you have learned how to integrate MongoDB into our application and also learned some basic commands. Hope you found this useful.

Keep Exploring!!!

--

--