How to bulk insert in mongodb using python Script on ubuntu 20.04


With MongoDB some times we need to insert bulk data using any kind of script for testing purpose.


In this post, We will build insert in MongoDB using Python3 script.


Step 1: Install Python Packages


You need to install the Python package by using the given command, It is a module to interact with python3 to MongoDB.

 sudo apt-get install python-pymongo -y  


String to make connection of MongoDB –  

# client = MongoClient('mongodb://user:password@host:port/database')


Step 2: Create Python Script


You need to create file and paste the following python code to bulk insertion.


Python code.

import pymongo
from pymongo import MongoClient
client = MongoClient('localhost')
print (client)
db = client.clients
clients = db.clients

for k in range(1000000):
    clients = db.clients.insert({"birthdate":"1970-01-01"});
print (k)

for l in range(1000000):
    clients = db.clients.insert({"birthdate":"1995-01-01"});

for f in range(1000000):
    clients = db.clients.insert({"birthdate":"1992-01-01"});

for i in range(1000000):
   clients = db.clients.insert({"name":"Tom"});

for j in range(1000000):
   clients = db.clients.insert({"name":"Tom hanks"});

print (db.clients.find({"birthdate":{"$lt":"1990-01-01"}}).count())
print (db.clients.find({"birthdate":{"$gt":"1980-01-01"}}).count())



Save and exit from the text editor.


Step 3: Execute the Python Script


Use the following command to execute the it.



We have successfully insert the bulk data in MongoDB on ubuntu machine, Still you have any issue leave a comment.













How to bulk insert in mongodb using python Script on ubuntu 20.04

Leave a Reply

Your email address will not be published. Required fields are marked *

Scroll to top