MongoDB Document Insertion using Python
In this page we will study, How to insert documents in Mongodb using Python code.
You know MongoDb use JSON file. Mongodb store the data in JSON format, first I am presenting a JSON file named test.json for testing
So i have my json named test.json.
Click to view JSON File
In above JSON file record field represents the actual record and ID field represent the number( may record number).
Now we'll insert the test.json file in mongodb using Python.
Let us study our first code.
Ensure that MongoDB service must be in running state, before execution of Python Program.
Just be sure that test.json is present in the same directory.
Now, let's go over each and every line.
The first two lines are importing the json and pymongo
Code line connection = pymongo.MongoClient
establishes a connection to the
database. The next line is db=connection.book handle to the
book database. Code line record1 = db.book_collection;
record1 contains a collection of records. In the next line, page
= open ("test.json", 'r')
the variable page contains the test.json
file. And in the following line, the variable parsed contains
the file in json format. If you want to view the records from the
MongoDB command line, use the commands as shown below.
The code line for the item in parsed["Records"]
that we are interested in parsed["Records"]
. The last line
inserts the records one by one in book_collection
If you want to view the records from the MongoDB
command line, use the following command:
For more help see the figure below.
Inserting MongoDB document Online
Here i am going to demonstrate, how to insert online JSON document into MongoDB database.
Here, you will be seeing couple of new lines. Here i've used new collection book_collection1
to differentiate from previous one.
Statement record1.drop() drop previous existing collection book_collection1
In 9th line statement page = urllib2.urlopen("http://l4wisdom.com/pymongo/code/insert/test.json")
open the test.json
file pass it to variable page
, the urllib2
library must be imported. Rest of code is same.
So this is the simple demo of MongoDB document insertion. In next page you will read how to retrieve data from mongoDB using Python code.