Skip to content

How to Query MongoDB Using Python: A Comprehensive Guide

MongoDB has been our go-to NoSQL database for several years due to its speed, scalability, and developer-friendly interface. In this guide, we will walk you through querying MongoDB using Python, step by step.

Getting Started with MongoDB and Python

Before we dive into querying MongoDB, we need to make sure that we have MongoDB installed and running on our machine. We also need to install the PyMongo library, which is a Python driver for MongoDB.

Installing PyMongo and Connecting

First, install the driver using pip:

bash
pip install pymongo

Then, establish a connection to the MongoDB server:

python
from pymongo import MongoClient
client = MongoClient("mongodb://localhost:27017/")
# Remember to close the connection when finished: client.close()

Selecting a Database

Once we have established a connection to the MongoDB server, we need to select a database to work with. In PyMongo, we can select a database by accessing it as an attribute of the MongoClient object.

select a MongoDB database in Python

python
db = client.mydatabase

Querying a Collection

Now that we have selected a database, we can query a collection within that database. In MongoDB, a collection is similar to a table in a relational database.

To query a collection, we need to call the find() method on the collection object. The find() method returns a cursor object, which we can iterate over to access the documents in the collection.

find method in MongoDB using Python

python
collection = db.mycollection
cursor = collection.find({})
for document in cursor:
    print(document)

This example retrieves all documents from the mycollection collection and prints them to the console.

Filtering Documents

To filter documents in a collection, we can pass a query object to the find() method. The query object specifies the criteria that documents must meet to be returned by the query.

filter documents in a MongoDB collection in Python

python
query = {"name": "John"}
cursor = collection.find(query)
for document in cursor:
    print(document)

Here, the query returns only documents where the name field matches "John".

Sorting Documents

To sort documents in a collection, we can chain the .sort() method on the cursor. The sort parameter specifies the field to sort by and the sort direction.

A query with sorting in MongoDB in Python

python
query = {}
sort = [("name", 1)]
cursor = collection.find(query).sort(sort)
for document in cursor:
    print(document)

This retrieves all documents and orders them by the name field in ascending order.

Limiting Results

To limit the number of documents returned by a query, we can call the limit() method on the cursor object.

Limiting a query's results in MongoDB in Python

python
query = {}
sort = [("name", 1)]
cursor = collection.find(query).sort(sort).limit(10)
for document in cursor:
    print(document)

This combines sorting with a limit, returning only the first 10 results.

Conclusion

This guide covered the fundamentals of connecting to MongoDB, selecting a database, and executing queries with Python. You now know how to filter, sort, and limit your results effectively. Use these techniques to build robust, scalable applications. Happy coding!

Dual-run preview — compare with live Symfony routes.