How to insert data in MongoDB using Python

Have a Database Problem? Speak with an Expert for Free
Get Started >>

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.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
# 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.

1
from pymongo import MongoClient

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

1
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.

1
2
3
4
5
try:
    connect = MongoClient()
    print("Connected successfully!")
except:
    print("Could not connect to MongoDB")

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.

1
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.

1
collection = db.demoCollection

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.

1
2
3
4
5
6
7
8
9
10
11
document1 = {
        "name":"John",
        "age":24,
        "location":"New York"
        }

document2 = {
        "name":"Sam",
        "age":21,
        "location":"Chicago"
        }

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.

1
2
collection.insert_one(document1)
collection.insert_one(document2)

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.

1
2
3
cursor = collection.find()
for record in cursor:
    print(record)

Let’s check the output.

1
2
3
Connected successfully!
{'_id': ObjectId('5d6bd4df25d75a89c4b1d4b0'), 'name': 'John', 'age': 24, 'location': 'New York'}
{'_id': ObjectId('5d6bd4df25d75a89c4b1d4b1'), 'name': 'Sam', 'age': 21, 'location': 'Chicago'}

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.