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 mongo.py file and paste the following python code to bulk insertion.
vim mongo.py
Python code.
import pymongo
from pymongo import MongoClient
client = MongoClient('localhost')
print (client)
db = client.clients
db.clients.count()
clients = db.clients
clients.find()
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"});
print(l)
for f in range(1000000):
clients = db.clients.insert({"birthdate":"1992-01-01"});
print(f)
for i in range(1000000):
clients = db.clients.insert({"name":"Tom"});
print(i)
for j in range(1000000):
clients = db.clients.insert({"name":"Tom hanks"});
print(j)
print (db.clients.find({"birthdate":{"$lt":"1990-01-01"}}).count())
print (db.clients.find({"birthdate":{"$gt":"1980-01-01"}}).count())
print(db.clients.count())
Save and exit from the text editor.
Step 3: Execute the Python Script
Use the following command to execute the it.
python3 mongo.py
Conclusion
We have successfully insert the bulk data in MongoDB on ubuntu machine, Still you have any issue leave a comment.
Your point of view caught my eye and was very interesting. Thanks. I have a question for you.