How to Insert a Document Into a MongoDB Collection Using Python
Introduction
Mastering the art of inserting MongoDB documents and MongoDB databases using Python and its PyMongo library is a great way to streamline managing your MongoDB collections. Adding documents is a common task you’ll likely complete on a regular basis and accomplishing it in a straightforward way leads to a more productive and efficient day. If you already know the steps to insert MongoDB documents Python and insert into Mongo DB collection PyMongo, skip the details in this tutorial and proceed to Just the Code.
Prerequisites
MongoDB – Install it. Next, in a terminal window, Test that it is installed and running correctly with the command
mongo --version
. You can also test it with themongo
command when you’re in the JavaScript interface Mongo shell.Python 3 – Download it. (Python 2 will be outdated soon. The examples in this tutorial require Python 3). Use the PIP package manager to install it:
1 | pip3 install pymongo |
- Create MongoDB document Python by creating a MongoDB database sample and collection. You will use the sample for inserting your collection and making API calls.
Import required modules and connect to MongoDB
Import all the Python modules including the
MongoClient
class.Create a new MongoDB driver instance:
1 2 | from pymongo import MongoClient mongo_client = MongoClient() |
A PyMongo collection object is needed for API calls
- You’ll be making API calls using
insert()
andinsert_one()
with the PyMongo collection object. Use themongo_client
object instance for that. Declare instances first:
1 2 3 | # declare database and collection instances db = mongo_client.some_database col = db.some_collection |
PyMongo 3.x insert_one() replaces insert()
- With PyMongo 3.x versions, the
insert_one()
replacesinsert()
for a single insertion, andinsert_many()
replacesinsertMany()
for inserting documents in bulk.
A DepreciationWarning is returned for outdated API call
- You’ll get the same type of
DepreciationWarning
error when you use the outdatedinsert()
instead ofinsert_one()
. Don’t worry about the attributes of the new method because that hasn’t changed.
Use insert_one() to add a Python dictionary to a MongoDB collection
- The parameters of
insert_one()
is where you’ll pass the Python dictionary for inserting a single document in a collection. In the example below, the API call is for a database instance attribute:
1 2 | # access the collection as an attribute of 'db' db.some_collection.insert_one( {"my_field" : "my value"} ) |
- Another way to make the API call is to use the method for the collection object and access
col
(the collection instance you created beforehand):
1 2 | # call collection object's method col.insert_one( {"field_42" : "another value"} ) |
Between the two, the first suggestion is recommended because it’s more reliable when it comes to verifying that it’s inserted into the right collection. In addition, it’s likely to be easier for the computer and humans to read. However, it’s good to know that you have options.
PyMongo 3.x id string is not returned in the result object
- This is new to Pymongo 3.x versions. To return the document’s
id
in theresult
object, useinserted_id
.:
1 2 | result = col.insert_one( {"field_42" : "another value"} ) print ("result _id:", result.inserted_id) # call 'inserted_id' |
Here’s an example of the outdated method used to access a MongoDB document’s _id
Create a Python dictionary to save time
- A Python dictionary saves you time in organizing your data for a MongoDB document. You can put MongoDB documents Python and organize everything in one place when you create a Python dictionary for a MongoDB document. This way, it will be more streamlined when you pass it for insertion.
Declare the MongoDB document’s Python dictionary
- Start with an empty dictionary. Use the
update()
method in Python’s dictionary for MongoDB field appending:
1 2 3 4 | doc_body = {} # dictionary object for MongoDB document doc_body.update( {"field 1" : 1234} ) doc_body.update( {"field 2" : 4321} ) print (doc_body) # should return: {'field 1': 1234, 'field 2': 4321} |
NOTE: Existing fields or keys will be updated to match the passed values if those fields or keys were already in the Python dictionary object.
Pass variables, functions, and objects into a Python dictionary
- Here’s a simple mathematical example of how easy it is for MongoDB fields in a document to be passed into a Python dictionary :
1 2 3 4 | doc_body = {} # dictionary object for MongoDB document all_ages = [23, 45, 10, 56, 32] doc_body.update({ "median age" : sum(all_ages)/len(all_ages) }) print (doc_body) # should return: {'median age': 33.2} |
>NOTE: When you use the update() method, it’s important to use brackets ({}
) around the updated values and keys.
- Another way to accomplish passing objects, variables, and functions is to do that at the same time you declare the dictionary. If you want, you can do this instead of the
update()
method.
1 2 3 4 5 6 7 8 9 10 11 12 13 | # import for timestamps import time all_ages = [23, 45, 10, 56, 32] # dictionary object for MongoDB document doc_body = { "timestamp" : time.time(), # returns float of epoch time "median age" : sum(all_ages)/len(all_ages) } print (doc_body) # should return: {'timestamp': 1559047217.7718751, 'median age': 33.2} |
Add the date and time in Python when you insert MongoDB documents
- Python’s PyMongo library’s
datetime.now()
method returns the current date and time in a datetime object when you insert a MongoDB document. Digits for the month, day, year, even seconds and microseconds can be returned if you like.
1 2 3 4 5 | # import datetime for date fields from datetime import datetime datetime_now = datetime.now() # pass this to a MongoDB doc print ("datetime_now:", datetime_now) print ("type datetime_now:", type(datetime_now)) |
- Here’s an example of what a successful result looks like:
1 2 | datetime_now: 2019-05-28 07:03:54.145193 type datetime_now: <class 'datetime.datetime'="'datetime.datetime'"> |
- Next, the
datetime_now
object is ready to pass to MongoDB document’s Python dictionary. You can append thedatetime_now
object if it already exists.
1 2 3 4 5 6 | doc_body.update( {"date" : datetime_now} ) print ("ndocument body:", doc_body) # make the API call to insert and return a result result = col.insert_one(doc_body) print ("nresult _id:", result.inserted_id) |
Insert the HTTP Message Body data into a MongoDB collection
- You can insert the HTTP Message Body string as a document into the MongoDB collection.
Use json.loads()
in Python to handle the message data in the HTTP request
- There’s more you can pass to a Python dictionary. Let’s say, for example, you want to insert a document and you make a
POST
request to do that. Then, you can pass it to a Python dictionary.
1 2 3 4 5 6 7 | # simulate an HTTP message body string POSTed from the client-side http_json_string = '''{ "new hires": [ {"name": "Wyman Leo", "age": "58", "sex": "male", "accounts": "wyman_leo", "join_date": "2008-09-19 16:51:54"}, {"name": "Romeo Armco", "age": "56", "sex": "male", "accounts": "romeo_armco", "join_date": "2017-07-17 20:31:38"} ] }''' |
- The
loads()
method from thejson
library in Python can make a Python dictionary out of the HTTP message string. After that, you can insert the dictionary object into a MongoDB collection.
1 2 3 4 5 6 7 | # convert the HTTP message JSON string into a Python dictionary import json doc_body = json.loads(http_json_string) # make the API call to insert the dictionary, and return a result result = col.insert_one(doc_body) print ("nresult _id:", result.inserted_id) |
Conclusion
The PyMongo library has been updated. Insert MongoDB collection Python documents using the old Python 2 version method of insert()
doesn’t work for Python 3.x versions. You’ll use the insert_one()
method instead to insert into MongoDB collection PyMongo. If you forget and use the outdated insert)
method, you’ll get aDepreciationWarning
object returned. This tutorial explained how to insert MongoDB documents Python and insert into MongoDB collection PyMongo.
Just the Code
Here’s the entire Python script to insert MongoDB documents Python and insert into Mongo DB collection PyMongo.
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 | #!/usr/bin/env python3 #-*- coding: utf-8 -*- from pymongo import MongoClient from datetime import datetime import time mongo_client = MongoClient('mongodb://localhost:27017') db = mongo_client.people col = db.ages print ("connected to MongoDB:", mongo_client["HOST"]) # data to pass into the Python dictionary object all_ages = [23, 45, 10, 56, 32] datetime_now = datetime.now() # pass this to a MongoDB doc print ("datetime_now:", datetime_now) # put the MongoDB document body together doc_body = { "timestamp" : time.time(), # returns float of epoch time "median age" : sum(all_ages)/len(all_ages), "date" : datetime_now } # update dictionary keys to add new # fields for the MongoDB document body doc_body.update( {"field int" : 1234} ) doc_body.update( {"field str" : "I am a string, yo!"} ) print ("ndocument body:", doc_body) result = col.insert_one(doc_body) # just print the result if using 2.x or older of PyMongo print ("nresult _id:", result.inserted_id) |
An id
that’s alphanumeric is shown at the end of a script that calls to insert a MongoDB document.
- Here’s an example of a successful terminal output.
MongoDB Compass Community GUI
- In the MongoDB Compass GUI, go to the document’s database and collection. You should see the document in which you used Python to insert into PyMongo.
1 2 3 4 5 6 | _id : 5ced3646d3c44562a22a19d4 timestamp : 1559049854.408565 median age : 33.2 date : 2019-05-28T08:24:14.408+00:00 field int : 1234 field str : "I am a string, yo!" |
Pilot the ObjectRocket Platform Free!
Try Fully-Managed CockroachDB, Elasticsearch, MongoDB, PostgreSQL (Beta) or Redis.
Get Started