How to insert data in MongoDB using Python

Introduction

Data can be inserted into MongoDB using the mongo shell but we can insert data in MongoDB using programming languages too. In this article, we will discuss how to insert documents into MongoDB using the Python programming language.

Python

Python is a high-level programming language. It is one of the most popular and widely used programming languages. There are many reasons why developers prefer python.

  1. Its syntax is very simple and easy to understand.
  2. It works perfectly with databases.
  3. It has a great collection of modules in its standard library.

Let’s discuss how can we insert data in MongoDB using Python.

Inserting data into MongoDB using Python

Before we start, here is the fully working Python code. Go through it and then we will discuss the code step by step.

# importing pymongo
from pymongo import MongoClient

# establing connection
try:
    connect = MongoClient()
    print("Connected successfully!!!")
except:
    print("Could not connect to MongoDB")

# connecting or switching to the database
db = connect.demoDB

# creating or switching to demoCollection
collection = db.demoCollection

# first document
document1 = {
        "name":"John",
        "age":24,
        "location":"New York"
        }
#second document
document2 = {
        "name":"Sam",
        "age":21,
        "location":"Chicago"
        }

# Inserting both document one by one
collection.insert_one(document1)
collection.insert_one(document2)



# Printing the data inserted
cursor = collection.find()
for record in cursor:
    print(record)

Let’s break this code down and understand what exactly is happening.

Importing MongoClient and establishing the connection

Pymongo is used to work with MongoDB in Python. As we are inserting data into MongoDB, first we need to establish a connection with it. To establish the connection, we need MongoClient. That is exactly what we did in the very first line of the program.

from pymongo import MongoClient

Now, we can use MongoClient in our program. Let’s establish a connection.

connect =  MongoClient()

We used a variable – connect, to establish a connection with the MongoClient. But here we can have exceptions such as connection failed with MongoClient. So in our program, we put the above part in a try-catch block.


GeSHi Error: GeSHi could not find the language py (using path /nas/content/live/orkbprod/wp-content/plugins/codecolorer/lib/geshi/) (code 2)

If the connection is successful, the code executes, otherwise, an exception will be thrown.

Connecting with a database and a collection

Now that we have a connection with MongoDB, we need to specify where to insert the data. Obviously, there will be a database. So to connect with a database, we will use the “connect” variable that we created earlier while establishing a connection with MongoClient.

db = connect.demoDB

demoDB is the database. If the database is present, it will switch to it, otherwise, a new database will be created.

In a database, there are collections. We need a collection now. We can use the “db” variable to create a connection with a collection.


GeSHi Error: GeSHi could not find the language py (using path /nas/content/live/orkbprod/wp-content/plugins/codecolorer/lib/geshi/) (code 2)

We now have a connection with demoDB database and the demoCollection collection.

Creating and inserting documents

The next step is creating the documents that will be inserted in the demoCollection. A MongoDB document should be created in JSON format. Let’s create one.


GeSHi Error: GeSHi could not find the language py (using path /nas/content/live/orkbprod/wp-content/plugins/codecolorer/lib/geshi/) (code 2)

Each of the above documents has three fields – name, age, and location.

It’s time for the important task – inserting data into the collection. To insert the documents one by one, we used the insert_one method.


GeSHi Error: GeSHi could not find the language py (using path /nas/content/live/orkbprod/wp-content/plugins/codecolorer/lib/geshi/) (code 2)

This is how we insert data into MongoDB using python.

Verify the output

To verify, if the data is inserted properly, we used the find method to retrieve all the documents from the demoCollection.


GeSHi Error: GeSHi could not find the language py (using path /nas/content/live/orkbprod/wp-content/plugins/codecolorer/lib/geshi/) (code 2)

Let’s check the output.


GeSHi Error: GeSHi could not find the language py (using path /nas/content/live/orkbprod/wp-content/plugins/codecolorer/lib/geshi/) (code 2)

Observe the output. First, it says “Connected successfully!” and then it prints the documents we inserted.

Conclusion

We can perform CRUD operations in MongoDB through the Python programming language. It is simple and easy. Here we used the MongoClient to establish a connection and then inserted data using the insert_one method. We hope you learned what you needed to solve your problem at hand. Thanks for joining us!

Pilot the ObjectRocket Platform Free!

Try Fully-Managed CockroachDB, Elasticsearch, MongoDB, PostgreSQL (Beta) or Redis.

Get Started

Keep in the know!

Subscribe to our emails and we’ll let you know what’s going on at ObjectRocket. We hate spam and make it easy to unsubscribe.