How To Access Collections For A MongoDB Database Using Python
If you’re a Python developer and you’d like to communicate with MongoDB in your scripts, it’s important to understand how the data is structured in the database. In MongoDB, the database is made up of groupings of documents called “collections”. You need to be able to access a collection before you can create, read, update, or delete documents; fortunately, the MongoDB client makes this task simple. In this article, we’ll explain how to access collections for a MongoDB database using Python.
Before we can jump into the Python code needed to access a MongoDB collection, we need to make sure all the system requirements for the task are in place. There are a few important prerequisites:
- First, you’ll need to make sure the MongoDB client for Python is installed. You can find out which version you have with this command:
- Next, you’ll need to install the MongoDB driver for Python 3. If you haven’t done so already, you can install it using
- Finally, be sure you have some collections on a MongoDB database that you can use to query. If you’ve just begun using MongoDB, a small test collection will suffice.
Get a list of MongoDB collections using Python
The first example we’ll look at involves obtaining a list of all collections that exist in your instance of MongoDB.
NOTE: A few important changes have been made to the MongoDB driver for Python since version
2.8. If you’re not sure what version of
pymongo is running, simply open up a Python interpreter environment and import the library, then call its
list_collection_names() method is depreciated since 2.9:
Please keep in mind that newer versions of the Python driver’s client (
pymongo.MongoClient) no longer support the
list_collection_names() method. You can use the
collection_names() method in its place, as shown in the example below:
print ("collections:", my_collections)
When you call this method, it will return a Python list of all of the database’s collection names. You can iterate through this list to print out your results. Keep in mind that each collection name can also be accessed as a dictionary attribute of the database object. We’ll refer to this again in a later example:
Verify that a MongoDB collection exists using Python
In some cases, you may not be sure whether a particular collection exists in MongoDB. If you try to query or perform other operations on a collection that doesn’t exist, you’ll get an error. To avoid this, you can use Python’s
hasattr() method to verify that the collection exists before trying to do anything else with it:
The method will return a
False boolean value depending on whether or not the collection exists. The image below shows an example of this method in action, where the output
True confirms to us that
Accessing a collection inside a MongoDB database
In our final example, we’ll access a particular collection inside the MongoDB database. Getting a collection in Python can be done using the code shown below:
Some collections have names where you won’t be able to use this attribute-style type of access; for example, collection names that contain spaces would cause Python errors if you tried to use the code above. In these cases, try using a dictionary-style type of access instead:
If you want to perform MongoDB operations from a Python script, you’ll need to know how to access the collections. The MongoDB client makes it easy to obtain a list of collections, verify that a collection exists and access an individual collection by name. With the step-by-step instructions provided in this article, you’ll be ready to access MongoDB collections from any Python script.
Here’s a complete script that accesses a MongoDB collection:
#-*- coding: utf-8 -*-
# import the MongoClient class from the library
from pymongo import MongoClient
# create an client instance of the MongoDB class
mongo_client = MongoClient()
# create an instance of 'some_database'
db = mongo_client.some_database
# create an instance of a collection from 'db'
col = db.some_collection
print ("col object:", col, "--", dir(col), "\n")
# get a list of a MongoDB database's collections
my_collections = database_object.collection_names()
print ("collections:", my_collections, "\n")
# check if the 'some_collection' attribute exists for the database
print ("some_collection exists:", hasattr(db, 'some_collection'))
# access a MongoDB collection name with spaces
col = db["Some Collection"]
print ("Some Collection:", col)
Pilot the ObjectRocket Platform Free!
Try Fully-Managed CockroachDB, Elasticsearch, MongoDB, PostgreSQL (Beta) or Redis.Get Started