Python MongoDB Tutorial – Querying Documents with PyMongo

Last updated 5 months, 1 week ago | 178 views 75     5

Tags:- Python MongoDB

Querying documents is at the core of working with databases. In MongoDB, queries are powerful and flexible, and when combined with Python using the PyMongo library, they become both simple and efficient to use.

In this tutorial, you'll learn how to perform various types of queries on a MongoDB collection using Python.


Table of Contents

  1. Introduction to MongoDB Queries

  2. Prerequisites

  3. Installing PyMongo

  4. Connecting to MongoDB

  5. Inserting Sample Data

  6. Basic Queries

  7. Query Operators

  8. Sorting Query Results

  9. Limiting Query Results

  10. Projecting Fields

  11. Complete Working Example

  12. Tips and Common Pitfalls


1. Introduction to MongoDB Queries

MongoDB uses JSON-like syntax for queries. You use key-value pairs and operators to filter documents. PyMongo allows you to express these queries using Python dictionaries.


⚙️ 2. Prerequisites

  • Python 3.x installed

  • MongoDB running locally or on MongoDB Atlas

  • Basic understanding of Python dictionaries and JSON


3. Installing PyMongo

Install the MongoDB driver for Python using pip:

pip install pymongo

4. Connecting to MongoDB

Local MongoDB server:

import pymongo

client = pymongo.MongoClient("mongodb://localhost:27017/")

MongoDB Atlas:

client = pymongo.MongoClient("mongodb+srv://<username>:<password>@<cluster>.mongodb.net/?retryWrites=true&w=majority")

5. Inserting Sample Data

Create a database and insert sample documents:

db = client["mydatabase"]
collection = db["users"]

collection.insert_many([
    {"name": "Alice", "age": 25, "email": "[email protected]", "active": True},
    {"name": "Bob", "age": 30, "email": "[email protected]", "active": False},
    {"name": "Charlie", "age": 28, "email": "[email protected]", "active": True},
    {"name": "Diana", "age": 35, "email": "[email protected]", "active": True}
])

6. Basic Queries

Find a user named "Alice":

user = collection.find_one({"name": "Alice"})
print(user)

Find all users aged 30:

results = collection.find({"age": 30})
for user in results:
    print(user)

⚙️ 7. Query Operators

MongoDB supports a wide range of operators:

Operator Description Example
$gt Greater than {"age": {"$gt": 25}}
$lt Less than {"age": {"$lt": 30}}
$gte Greater than or equal {"age": {"$gte": 30}}
$lte Less than or equal {"age": {"$lte": 25}}
$ne Not equal {"name": {"$ne": "Alice"}}
$in Matches any in array {"age": {"$in": [25, 30]}}
$and Logical AND {"$and": [{"age": {"$gt": 25}}, {"active": True}]}
$or Logical OR {"$or": [{"age": 25}, {"active": False}]}

Example: Users over 25 and active

query = {"$and": [{"age": {"$gt": 25}}, {"active": True}]}
for user in collection.find(query):
    print(user)

8. Sorting Query Results

Sort users by age ascending:

for user in collection.find().sort("age", 1):
    print(user)

Sort by age descending:

for user in collection.find().sort("age", -1):
    print(user)

9. Limiting Query Results

Limit the number of returned documents:

for user in collection.find().limit(2):
    print(user)

10. Projecting Fields

Show only specific fields in results:

for user in collection.find({}, {"_id": 0, "name": 1, "email": 1}):
    print(user)

This will exclude _id and show only name and email.


11. Complete Working Example

import pymongo

# Connect to MongoDB
client = pymongo.MongoClient("mongodb://localhost:27017/")
db = client["mydatabase"]
collection = db["users"]

# Insert sample data (if not already present)
if collection.count_documents({}) == 0:
    collection.insert_many([
        {"name": "Alice", "age": 25, "email": "[email protected]", "active": True},
        {"name": "Bob", "age": 30, "email": "[email protected]", "active": False},
        {"name": "Charlie", "age": 28, "email": "[email protected]", "active": True},
        {"name": "Diana", "age": 35, "email": "[email protected]", "active": True}
    ])

# Query with filter and projection
query = {"age": {"$gt": 25}}
projection = {"_id": 0, "name": 1, "age": 1}

print("Users older than 25:")
for user in collection.find(query, projection).sort("age", 1).limit(3):
    print(user)

12. Tips and Common Pitfalls

Tip / Pitfall Solution / Advice
Case-sensitive field names Ensure exact field name matches
Querying for non-existing fields Returns no results instead of errors
$in works only on lists Provide an array of values
Use projection to improve performance Especially when documents are large
Don't forget to iterate over cursors find() returns a cursor, not a list
Compound queries require $and, $or Combine multiple conditions properly

✅ Conclusion

MongoDB queries with Python and PyMongo are intuitive, flexible, and powerful. From basic filtering to advanced logical operators and projections, you can easily manipulate and retrieve the exact data you need.

Understanding MongoDB queries is key to leveraging its power in real-world Python applications, whether for analytics, web development, or automation.