How to Insert MongoDB Documents Using Python

Introduction

Appending a MongoDB collection of documents is a basic part of document database management. Sometimes you’ll just need to insert one document; other times, you’ll need to insert many. The Python pymongo driver can help you efficiently accomplish either task.

Now is a great time to learn the way to insert MongoDB document Python because the insert_one() method and the pymongo driver were first introduced in PyMongo version 3. The older versions of PyMongo use the insertOne() method, which is less pythonic, so to speak. In other words, they’re obsolete.

Since the PyMongo version 3.x and the later ones contain the driver pymongo, you can harness its capabilities in all your coding tasks including adding documents to collections. Find out how to insert MongoDB documents using Python with this step-by-step tutorial today. If you’re already familiar with the insert document MongoDB Python process, and want to skip the details, feel free to go to Just the Code.

Prerequisites

  • MongoDB – Install MongoDB on the server.

  • Open a terminal window and check that it has been installed with the following command:

mongo --version
  • Python 3 – Install the pymongo driver, version Python 3.

>NOTE: Python 2 will soon be defunct.

  • Here’s a tip for a fast install of Python 3: Use IDLE or any other Python environment you prefer. At the command line type pip3 install pymongo. Check which driver version you have with it as well.
import pymongo
pymongo.version

*Look for the version number in a string. For example, '3.4.0' is a hypothetical version number.

  • If you see ImportError in the results, reinstall Python because pymongo failed to properly install.

Use the Python Class MongoClient to Connect MongoDB

  • The class library needs to be imported at the script’s beginning for instantiation, the initialization of settings of new objects. Use the following command:
#!/usr/bin/env python3
from pymongo import MongoClient
  • Now, you’re ready to create a MongoDB driver new instance:
mongo_client = MongoClient()

Pass the Parameters of the Port and Domain

  • Here’s a URI string to explicitly pass both the port parameters and the domain right into MongoDB using MongoClient().
mongo_client = MongoClient('mongodb://localhost:27017')
  • If you want to handle them each by themselves, pass the (Python) integer for the port and then for the domain name, use a string.

  • Alternatively, pass both as parameters, explicitly.

mongo_client = MongoClient('localhost', 27017)

Verify your MongoDB server connection with a print statement in Python

  • Here’s an environment of IDLE Python showing verification of an instance of the MongoDB client. Screenshot of a MongoDB client instance in the IDLE Python environment

MongoDB is Ready for a Collection and Database

  • Use create_collection() to create a database as shown here:
db = mongo_client.some_database # access "some_database"

# create a new collection for the "some_database" database
col = mongo_client.db.create_collection('collection_name')
  • If you like, pass options such as the collection’s size and pipeline into the create_collection().

  • You can opt to declare a collection_object. This allows you to create the document, collection, and database–all at once. The benefit of doing creating the document this way is that it may save you some time writing code. The MongoDB server won’t update until the document has been created.

collection_object = db.some_collection
  • The above shows the declared collection object, but the MongoDB server has nothing written to it yet.

>NOTE: There are some limitations to the Connection class where it concerns the PyMongo 3 driver. Only in previous versions of PyMongo can the script accept the importation of the Connection class. This occurs because the Connection class for the library is outdated.

With the PyMongo 3 driver, an attempt to import the Connection class in Python IDLE returns an ImportError.

Screenshot of Python IDLE returning an ImportError because Connection is no longer a class name for the library

How to Insert Document MongoDB Python

  • MongoDB uses the JSON format and the python_dict Python dictionary object matches it well.

  • The example below shows KVP (key-value pairs) as unique identifiers for line values and their stated corresponding fields.

python_dict = {
"field1" : "value for field 1",
"field2" : "value for field 2",
"field3" : "value for field 3"
}
  • Now, the python_dict that was just created can be put into the database as the document. Insert it using the pymongo insertion method.

Create a New Document in MongoDB withinsert_one()

  • After instantiation of the new collection and database, create document MongoDB Python and add the document with insert_one().
result_object = collection_object.insert_one(python_dict)

Get Feedback from pymongo.results.InsertOneResult

  • You can parse the object pymongo.results.InsertOneResult to get useful API response feedback.
  • Use the result_object.acknowledged and result_object.inserted_id
result_object.acknowledged # <-- should return: True
result_object.inserted_id # <--- returns a bson ObjectId
  • Another way to do an API call is by the ObjectId of the document that was inserted. At the call’s end, call the attribute inserted_id like this:
result_id = collection_object.insert_one(another_doc).inserted_id

>NOTE: About “ID” fields. You could think of them as unique index document MongoDB Python types of fields or index document MongoDB collection Python fields. The unique IDs such as ObjectID ensures that no two documents’ values are alike. By the way, Indexing speeds up finding relevant documents in your queries.

  • The ObjectID BSON for the document has an alphanumeric ID that is unique. You’ll see it when the API call’s returned result is passed to the print function in Python.
ObjectId('5cda6f216654445ed36aba1a')

This example shows within the Python IDLE environment the inserted_id function. What’s more, the page indicates that for a collection, to add documents, PyMongo was used.

Screenshot of Python's IDLE environment using PyMongo to insert documents into a collection

How to use the insert_many() method to insert multiple MongoDB documents

  • With the method, insert_many(), you can insert Python dictionaries by the list as opposed to one at a time.

  • To begin, start with an empty list and delcare it with this command:

my_documents = []

Add documents to a Python list

  • When you want to create a document MongoDB Python, that is to create a MongoDB document, create a Python dictionary for it.

  • Use my_documents Create a Python dictionary for each MongoDB document you’d like to create.

# Add the MongoDB documents to a Python list
my_documents += [{'field': 'value'}]
my_documents.append({'field': 'value'})
my_documents = my_documents + [{'field': 'value'}]

Use the method insert_many() to pass the MongoDB documents list

  • A result object will be returned when you pass the list of MongoDB documents via the insert_many() method.
result = collection_object.insert_many(my_documents)
print (result)
  • Here is a successful returned result object looks like:
<pymongo.results.insertmanyresult object="object" at="at" 0x10cd257e0="0x10cd257e0">

Iterate a collection of documents in MongoDB with the for loop

  • Below is an example of the Python IDLE environment using the for loop method and insert_many to add documents to a collection in MongoDB.

Screenshot of Python's IDLE environment inserting many documents into a MongoDB collection

>TIP: Now you can index document MongoDB collection Python for your updated collection to streamline finding your documents. You can also index document MongoDB Python if you just added them separately. Indexing improves scanning your queries.

Conclusion

Insert MongoDB document Python is more simplified when you use the insert_one() method to insert one document. You can also streamline the process of inserting more than one document at a time when you do it with insert_many() method. What makes it all happen expeditiously is pymongo, Python’s driver which was first available in Python version 3.x. Now it’s a standard feature in later editions of Python. Take advantage of the insert methods discussed in this tutorial. Try them on your next coding project and you’ll likely save time while increasing productivity.

Just the Code

Here’ the complete script showing how to use Python to insert one or more MongoDB documents into a collection.

#!/usr/bin/env python3
#-*- coding: utf-8 -*-

# import the pymongo library
from pymongo
import time

# create a client instance with explicitly passed host parameter
mongo_client = pymongo.MongoClient('mongodb://localhost:27017')

# create a new MongoDB database object for the client
db = mongo_client.new_database

# create a collection object that will be
# used to call 'insert' methods
col = db["Collection With Spaces"]


# create the Python dictionaries to be passed as Mongo documents
some_doc = {'field_str': 'a very unique string', 'field_int' : 1234}

# create another document with a timestamp
another_doc = {'field_str': 'some string', 'timestamp' : time.time()}

# call the 'insert_one()' method to insert a doc
result = col.insert_one(some_doc).inserted_id
print ("nresult of insertion:", result)


# insert another document
result = col.insert_one(another_doc).inserted_id
print ("result of insertion:", result)

# create a list and append several documents
# (in the form of Python dictionaries) to it
my_documents = []

# three different ways to append items to a Python list
my_documents += [{'field': 'value'}]
my_documents.append({'field': 'value'})
my_documents = my_documents + [{'field': 'value'}]

# call the `insert_many()` method and return a result
result = col.insert_many(my_documents)
print ('ninsert_many result:',result)

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.