Link Search Menu Expand Document

Python with MongoDB

The user can get started with MongoDB and their favorite programming language by leveraging one of its drivers, mostly maintained by MongoDB engineers and open-source community members. MongoDB provides a native Python driver, PyMongo, and a team of Driver engineers dedicated to developing the driver to meet the needs of the Python community, ensuring that MongoDB and Python function smoothly together.

The user can begin working with MongoDB right away by using a free MongoDB cluster provided by MongoDB Atlas. MongoDB Atlas is a database service that permits the user to specify the size of your database and receive a connection string.

Install Python Driver

Even though additional drivers built by the community exist, PyMongo is the official Python driver for MongoDB. The pip package management system is the simplest approach to installing the driver. Run the following commands from the command line:

python -m pip install pymongo

Note that if the user is utilizing the Atlas M0 (Free Tier) cluster, Python 2.7.9+ and Python 3.4 or newer are required. The “python —version” and “pip list” commands can be used to determine which version of Python and PyMongo is in use.

from pymongo import MongoClient
# pprint library is used to make the output look more pretty
from pprint import pprint
# connect to MongoDB, change the << MONGODB URL >> to reflect your own connection string
client = MongoClient(<<MONGODB URL>>)
# Issue the serverStatus command and print the results

Replace the “<>” with the MongoDB connection string. Save it as “” and run it from the command line with “python”

Example Output

{u'asserts': {u'msg': 0,
              u'regular': 0,
              u'rollovers': 0,
              u'user': 0,
              u'warning': 0},
 u'connections': {u'available': 96, u'current': 4, u'totalCreated': 174L},
 u'extra_info': {u'note': u'fields vary by platform', u'page_faults': 0},
 u'host': u'',
 u'localTime': datetime.datetime(2017, 4, 4, 0, 18, 45, 616000),

The ‘u’ character in the python output indicates that the strings are saved in Unicode. This example also employs the pprint library, which is unrelated to MongoDB and is used solely to structure and visually please output from a console.

In this example, we’re connecting to our MongoDB instance and running “db.serverStatus()” (reference). This command returns data about the MongoDB instance and executes a command on MongoDB in this example.

The application is ready to use if it runs correctly!

Exploring Documents and Collections

MongoDB holds data in the form of documents. Documents are not like Microsoft Word or Adobe PDF files, but JSON files that adhere to the JSON specification.

Documents can have arrays and subdocuments in addition to key/value pairs. The data itself can be of several types, including geographic, decimal, and ISODate, to mention a few. MongoDB internally maintains a binary representation of JSON known as BSON. It enables MongoDB to support data types such as decimal that are not defined in the JSON specification.

In MongoDB, a collection is a document’s container. Collections are stored in databases. Relational databases are comparable to this class.

Relational conceptMongoDB equivalent

Data can be stored in papers for a variety of reasons. While a more detailed discussion is outside the scope of this post, our basic Python scripts demonstrate some of the benefits, such as dynamic, adjustable schema and the ability to store arrays.

Unicode String

The data in MongoDB is stored in BSON format. Because BSON strings are encoded in UTF-8, PyMongo must ensure that any stored strings are valid UTF-8 data. Regular strings (type’str’>) are validated and saved in their original state. Unicode strings (of the type ‘Unicode>) are first encoded in UTF-8. Because PyMongo decodes each BSON string to a Python Unicode string rather than plain str, our sample string appears in the Python shell as u’Mike’ rather than ‘Mike.’

>>> post_id
>>> pprint.pprint(posts.find_one({"_id": post_id}))
{u'_id': ObjectId('...'),
 u'author': u'Mike',
 u'date': datetime.datetime(...),
 u'tags': [u'mongodb', u'python', u'pymongo'],
 u'text': u'My first blog post!'}

Other useful articles:

Back to top

© , Learn Python 101 — All Rights Reserved - Terms of Use - Privacy Policy