Using the Query DSL¶
Pydongo's query engine is built on top of Python-native expressions, making MongoDB queries feel natural and type-safe using your Pydantic models.
This page covers how to use FieldExpression
and CollectionFilterExpression
to write expressive, composable queries β without writing raw MongoDB dictionaries.
π Field Expressions¶
Every field on your model becomes a FieldExpression
in a collection:
collection = as_collection(User, driver)
collection.age # FieldExpression
This enables query expressions like:
collection.age > 25
collection.name == "Alice"
collection.age <= 60
You can use these in .find()
or .find_one()
:
collection.find(collection.age > 30)
collection.find_one((collection.age > 20) & (collection.name != "Bob"))
π Logical Composition¶
All field expressions produce a CollectionFilterExpression
, which can be composed:
Operator | Description |
---|---|
& |
Logical AND |
| |
Logical OR |
~ |
Logical NOT |
expr = (collection.age > 18) & (collection.name != "Bob")
collection.find(expr)
π Array Field Expressions¶
Array fields get additional operators via ArrayFieldExpression
.
class User(BaseModel):
name: str
tags: List[str]
collection = as_collection(User, driver)
collection.tags.contains("admin")
collection.tags.excludes("guest")
collection.tags.matches(["admin", "moderator"])
collection.tags.size() > 2
Supported:
- contains(value)
β $in
- excludes(value)
β $nin
- matches(list)
β $all
or exact match
- size() > 2
β $expr: {$gt: [{$size: "$tags"}, 2]}
βοΈ Nested Fields¶
You can access subfields using dot notation automatically:
class Address(BaseModel):
city: str
class User(BaseModel):
name: str
address: Address
collection = as_collection(User, driver)
collection.address.city == "Lagos"
This will generate:
{"address.city": {"$eq": "Lagos"}}
π€ Serialization¶
All expressions can be turned into MongoDB queries via .serialize()
:
expr = (collection.age > 18) & (collection.name == "Alice")
query = expr.serialize()
# { "$and": [{"age": {"$gt": 18}}, {"name": {"$eq": "Alice"}}] }
β Summary¶
- Use Python syntax for building MongoDB queries
- Supports scalar fields, arrays, and nested structures
- Output is always a valid MongoDB filter object
- Integrates seamlessly with
collection.find()
,find_one()
, and.count()
Pydongoβs DSL gives you clean, powerful Mongo filters β without ever writing a manual $and
, $gt
, or $in
.