Skip to main content
The Collection class represents a non-transactional collection handle.

Collection management

close

Frees the collection handle.
def close() -> None
Example:
coll = db.get_collection("users")
try:
    # Use collection
    pass
finally:
    coll.close()

Context manager support

Use the with statement for automatic resource cleanup. Example:
with db.get_collection("users") as coll:
    doc_id = coll.insert({"name": "Bob", "age": 25})
    # Collection is automatically closed when exiting the block

name

Gets the collection name.
def name() -> str
str
str
Collection name

Basic CRUD operations

insert

Inserts a document.
def insert(doc: Dict[str, Any]) -> str
doc
Dict[str, Any]
required
Document to insert
str
str
ID of the inserted document
Example:
coll = db.get_collection("users")
doc_id = coll.insert({"name": "Alice", "age": 30})
print(f"Inserted: {doc_id}")

find_by_id

Finds a document by ID.
def find_by_id(doc_id: str) -> Optional[Dict[str, Any]]
doc_id
str
required
Document ID to find
Optional[Dict[str, Any]]
Optional[Dict[str, Any]]
Document if found, None otherwise
Example:
doc = coll.find_by_id("user123")
if doc:
    print(f"Found: {doc}")

update_by_id

Updates a document by ID.
def update_by_id(doc_id: str, doc: Dict[str, Any]) -> None
doc_id
str
required
Document ID to update
doc
Dict[str, Any]
required
Updated document data
Example:
coll.update_by_id("user123", {"name": "Alice Smith", "age": 31})

delete_by_id

Deletes a document by ID.
def delete_by_id(doc_id: str) -> None
doc_id
str
required
Document ID to delete
Example:
coll.delete_by_id("user123")

find_all

Finds all documents.
def find_all() -> List[Dict[str, Any]]
List[Dict[str, Any]]
List[Dict[str, Any]]
List of all documents
Example:
all_docs = coll.find_all()
for doc in all_docs:
    print(doc)

count

Counts all documents.
def count() -> int
int
int
Number of documents
Example:
total = coll.count()
print(f"Total documents: {total}")

Query and filter operations

find

Finds documents matching a filter.
def find(filter_str: str) -> List[Dict[str, Any]]
filter_str
str
required
Query filter expression
List[Dict[str, Any]]
List[Dict[str, Any]]
List of matching documents
Example:
results = coll.find("age > 25")
for user in results:
    print(user)

find_one

Finds first document matching a filter.
def find_one(filter_str: str) -> Optional[Dict[str, Any]]
filter_str
str
required
Query filter expression
Optional[Dict[str, Any]]
Optional[Dict[str, Any]]
First matching document, or None
Example:
user = coll.find_one("email == '[email protected]'")
if user:
    print(f"Found: {user}")

update

Updates all documents matching a filter. Returns count updated.
def update(filter_str: str, update: Dict[str, Any]) -> int
filter_str
str
required
Query filter expression
update
Dict[str, Any]
required
Update data
int
int
Number of documents updated
Example:
count = coll.update("age > 25", {"verified": True})
print(f"Updated {count} documents")

update_one

Updates first document matching a filter. Returns True if updated.
def update_one(filter_str: str, update: Dict[str, Any]) -> bool
filter_str
str
required
Query filter expression
update
Dict[str, Any]
required
Update data
bool
bool
True if a document was updated
Example:
updated = coll.update_one("email == '[email protected]'", {"verified": True})
if updated:
    print("Document updated")

delete

Deletes all documents matching a filter. Returns count deleted.
def delete(filter_str: str) -> int
filter_str
str
required
Query filter expression
int
int
Number of documents deleted
Example:
count = coll.delete("age < 18")
print(f"Deleted {count} documents")

delete_one

Deletes first document matching a filter. Returns True if deleted.
def delete_one(filter_str: str) -> bool
filter_str
str
required
Query filter expression
bool
bool
True if a document was deleted
Example:
deleted = coll.delete_one("email == '[email protected]'")
if deleted:
    print("Document deleted")

Upsert operations

upsert_by_id

Upserts a document by ID. Returns UpsertResult with id and inserted flag.
def upsert_by_id(doc_id: str, doc: Dict[str, Any]) -> UpsertResult
doc_id
str
required
Document ID
doc
Dict[str, Any]
required
Document data
UpsertResult
UpsertResult
Result containing id and whether it was inserted or updated
Example:
result = coll.upsert_by_id("user123", {"name": "Alice", "age": 30})
if result.inserted:
    print(f"Inserted new document: {result.id}")
else:
    print(f"Updated existing document: {result.id}")

upsert

Upserts a document matching a filter. Returns UpsertResult with id and inserted flag.
def upsert(filter_str: str, doc: Dict[str, Any]) -> UpsertResult
filter_str
str
required
Query filter expression
doc
Dict[str, Any]
required
Document data
UpsertResult
UpsertResult
Result containing id and whether it was inserted or updated
Example:
result = coll.upsert("email == '[email protected]'", {
    "name": "Alice",
    "email": "[email protected]",
    "age": 30
})

Bulk operations

insert_many

Inserts multiple documents. Returns list of IDs.
def insert_many(docs: List[Dict[str, Any]]) -> List[str]
docs
List[Dict[str, Any]]
required
List of documents to insert
List[str]
List[str]
List of inserted document IDs
Example:
ids = coll.insert_many([
    {"name": "Alice", "age": 30},
    {"name": "Bob", "age": 25},
    {"name": "Charlie", "age": 35}
])
print(f"Inserted {len(ids)} documents")

bulk_write

Executes multiple operations in a transaction.
def bulk_write(operations: List[Dict[str, Any]], ordered: bool = True) -> Dict[str, Any]
operations
List[Dict[str, Any]]
required
List of bulk operations
ordered
bool
default:"True"
Whether to execute operations in order
Dict[str, Any]
Dict[str, Any]
Result with statistics for each operation type
Example:
operations = [
    {"op": "insert", "doc": {"name": "Alice", "age": 30}},
    {"op": "update", "filter": "age > 25", "update": {"verified": True}},
    {"op": "delete", "filter": "age < 18"}
]
result = coll.bulk_write(operations)
print(f"Bulk write result: {result}")

Advanced operations

distinct

Gets distinct values for a field.
def distinct(field: str) -> List[Any]
field
str
required
Field name
List[Any]
List[Any]
List of distinct values
Example:
ages = coll.distinct("age")
print(f"Distinct ages: {ages}")

count_distinct

Counts distinct values for a field.
def count_distinct(field: str) -> int
field
str
required
Field name
int
int
Number of distinct values
Example:
count = coll.count_distinct("city")
print(f"Number of unique cities: {count}")
Performs full-text search.
def search(query: str) -> List[Dict[str, Any]]
query
str
required
Search query
List[Dict[str, Any]]
List[Dict[str, Any]]
List of matching documents
Example:
results = coll.search("python database")
for doc in results:
    print(doc)

count_with_query

Counts documents matching a filter.
def count_with_query(filter_str: str) -> int
filter_str
str
required
Query filter expression
int
int
Number of matching documents
Example:
count = coll.count_with_query("age > 25")
print(f"Users over 25: {count}")

aggregate

Executes an aggregation pipeline.
def aggregate(pipeline: List[Dict[str, Any]]) -> List[Dict[str, Any]]
pipeline
List[Dict[str, Any]]
required
Aggregation pipeline stages
List[Dict[str, Any]]
List[Dict[str, Any]]
Aggregation results
Example:
pipeline = [
    {"$match": {"age": {">=": 18}}},
    {"$group": {"_id": "$city", "count": {"$sum": 1}}},
    {"$sort": {"count": -1}}
]
results = coll.aggregate(pipeline)
for result in results:
    print(result)

Query builder helpers

query_with_options

Executes a query with all options.
def query_with_options(
    filter_str: Optional[str] = None,
    sort_field: Optional[str] = None,
    sort_asc: bool = True,
    limit: int = 0,
    skip: int = 0,
    project_fields: Optional[List[str]] = None,
    exclude_fields: Optional[List[str]] = None,
) -> List[Dict[str, Any]]
filter_str
Optional[str]
Query filter expression
sort_field
Optional[str]
Field to sort by
sort_asc
bool
default:"True"
Sort in ascending order
limit
int
default:"0"
Maximum number of results (0 = no limit)
skip
int
default:"0"
Number of results to skip
project_fields
Optional[List[str]]
Fields to include in results
exclude_fields
Optional[List[str]]
Fields to exclude from results
List[Dict[str, Any]]
List[Dict[str, Any]]
List of matching documents
Example:
results = coll.query_with_options(
    filter_str="age > 25",
    sort_field="age",
    sort_asc=False,
    limit=10,
    skip=5,
    project_fields=["name", "age"]
)

query_count

Counts documents with query options.
def query_count(filter_str: Optional[str] = None, skip: int = 0, limit: int = 0) -> int
filter_str
Optional[str]
Query filter expression
skip
int
default:"0"
Number of results to skip
limit
int
default:"0"
Maximum number of results to count
int
int
Number of matching documents

query_first

Gets the first document matching a query.
def query_first(
    filter_str: Optional[str] = None,
    sort_field: Optional[str] = None,
    sort_asc: bool = True,
) -> Optional[Dict[str, Any]]
filter_str
Optional[str]
Query filter expression
sort_field
Optional[str]
Field to sort by
sort_asc
bool
default:"True"
Sort in ascending order
Optional[Dict[str, Any]]
Optional[Dict[str, Any]]
First matching document, or None
Example:
oldest = coll.query_first(sort_field="age", sort_asc=False)
if oldest:
    print(f"Oldest user: {oldest}")

Watch and change streams

watch

Starts watching for changes on the collection.
def watch(
    callback: Callable[[str, str, Optional[Dict[str, Any]]], None],
    filter_str: Optional[str] = None,
) -> WatchHandle
callback
Callable[[str, str, Optional[Dict[str, Any]]], None]
required
Callback function receiving (operation, doc_id, document)
filter_str
Optional[str]
Optional filter for watched events
WatchHandle
WatchHandle
Handle to stop the watch
Example:
def on_change(op, doc_id, doc):
    print(f"{op}: {doc_id}")
    if doc:
        print(f"  Data: {doc}")

handle = coll.watch(on_change)
# ... later ...
handle.stop()

Build docs developers (and LLMs) love