Official Python driver for MongoDB providing comprehensive tools for database operations, BSON handling, and GridFS file storage
—
Database management, collection operations, document CRUD operations, indexing, and basic query functionality.
Access and manage databases within a MongoDB deployment.
class Database:
def __init__(self, client, name, **kwargs):
"""
Database instance for operations.
Parameters:
- client: MongoClient instance
- name: database name
- codec_options: BSON codec options
- read_preference: read preference
- write_concern: write concern
- read_concern: read concern
"""
def get_collection(self, name, **kwargs):
"""
Get a collection instance.
Parameters:
- name: collection name
- codec_options: BSON codec options
- read_preference: read preference
- write_concern: write concern
- read_concern: read concern
Returns:
Collection instance
"""
def list_collection_names(self, session=None, filter=None, **kwargs):
"""
List collection names in the database.
Parameters:
- session: optional ClientSession
- filter: optional filter criteria
Returns:
List of collection names
"""
def list_collections(self, session=None, filter=None, **kwargs):
"""
List collections with metadata.
Parameters:
- session: optional ClientSession
- filter: optional filter criteria
Returns:
CommandCursor with collection information
"""
def create_collection(self, name, **kwargs):
"""
Create a collection.
Parameters:
- name: collection name
- capped: create capped collection
- size: maximum size in bytes (capped collections)
- max: maximum number of documents (capped collections)
- validator: document validation rules
- validationLevel: validation strictness
- validationAction: action on validation failure
- session: optional ClientSession
Returns:
Collection instance
"""
def drop_collection(self, name_or_collection, session=None):
"""
Drop a collection.
Parameters:
- name_or_collection: collection name or Collection instance
- session: optional ClientSession
"""
@property
def client(self):
"""
MongoClient instance for this database.
Returns:
MongoClient instance
"""
@property
def name(self):
"""
Database name.
Returns:
str: Database name
"""Core document operations for creating, reading, updating, and deleting documents.
class Collection:
def insert_one(self, document, bypass_document_validation=False, session=None):
"""
Insert a single document.
Parameters:
- document: document to insert
- bypass_document_validation: skip validation
- session: optional ClientSession
Returns:
InsertOneResult with inserted_id
"""
def insert_many(
self,
documents,
ordered=True,
bypass_document_validation=False,
session=None
):
"""
Insert multiple documents.
Parameters:
- documents: sequence of documents
- ordered: stop on first error if True
- bypass_document_validation: skip validation
- session: optional ClientSession
Returns:
InsertManyResult with inserted_ids
"""
def find_one(self, filter=None, *args, **kwargs):
"""
Find a single document.
Parameters:
- filter: query criteria
- projection: fields to return
- skip: number of documents to skip
- sort: sort specification
- max_time_ms: maximum execution time
- session: optional ClientSession
Returns:
Document or None
"""
def find(self, filter=None, projection=None, skip=0, limit=0, **kwargs):
"""
Find documents matching criteria.
Parameters:
- filter: query criteria
- projection: fields to return
- skip: number of documents to skip
- limit: maximum number of documents
- sort: sort specification
- batch_size: cursor batch size
- max_time_ms: maximum execution time
- session: optional ClientSession
Returns:
Cursor instance
"""
def update_one(
self,
filter,
update,
upsert=False,
bypass_document_validation=False,
session=None,
**kwargs
):
"""
Update a single document.
Parameters:
- filter: query criteria
- update: update specification
- upsert: insert if no match found
- bypass_document_validation: skip validation
- session: optional ClientSession
Returns:
UpdateResult
"""
def update_many(
self,
filter,
update,
upsert=False,
bypass_document_validation=False,
session=None,
**kwargs
):
"""
Update multiple documents.
Parameters:
- filter: query criteria
- update: update specification
- upsert: insert if no match found
- bypass_document_validation: skip validation
- session: optional ClientSession
Returns:
UpdateResult
"""
def replace_one(
self,
filter,
replacement,
upsert=False,
bypass_document_validation=False,
session=None,
**kwargs
):
"""
Replace a single document.
Parameters:
- filter: query criteria
- replacement: replacement document
- upsert: insert if no match found
- bypass_document_validation: skip validation
- session: optional ClientSession
Returns:
UpdateResult
"""
def delete_one(self, filter, session=None, **kwargs):
"""
Delete a single document.
Parameters:
- filter: query criteria
- session: optional ClientSession
Returns:
DeleteResult with deleted_count
"""
def delete_many(self, filter, session=None, **kwargs):
"""
Delete multiple documents.
Parameters:
- filter: query criteria
- session: optional ClientSession
Returns:
DeleteResult with deleted_count
"""
def count_documents(self, filter, session=None, **kwargs):
"""
Count documents matching criteria.
Parameters:
- filter: query criteria
- skip: number of documents to skip
- limit: maximum number to count
- max_time_ms: maximum execution time
- session: optional ClientSession
Returns:
int: Document count
"""
def estimated_document_count(self, **kwargs):
"""
Estimate total document count.
Parameters:
- max_time_ms: maximum execution time
Returns:
int: Estimated document count
"""
def distinct(self, key, filter=None, session=None, **kwargs):
"""
Get distinct values for a field.
Parameters:
- key: field name
- filter: query criteria
- max_time_ms: maximum execution time
- session: optional ClientSession
Returns:
List of distinct values
"""Atomic find-and-modify operations that return documents while modifying them.
class Collection:
def find_one_and_delete(self, filter, projection=None, sort=None, session=None, **kwargs):
"""
Find and delete a document atomically.
Parameters:
- filter: query criteria
- projection: fields to return
- sort: sort specification
- max_time_ms: maximum execution time
- session: optional ClientSession
Returns:
Deleted document or None
"""
def find_one_and_replace(
self,
filter,
replacement,
projection=None,
sort=None,
upsert=False,
return_document=ReturnDocument.BEFORE,
session=None,
**kwargs
):
"""
Find and replace a document atomically.
Parameters:
- filter: query criteria
- replacement: replacement document
- projection: fields to return
- sort: sort specification
- upsert: insert if no match found
- return_document: return original or modified document
- bypass_document_validation: skip validation
- max_time_ms: maximum execution time
- session: optional ClientSession
Returns:
Original or modified document
"""
def find_one_and_update(
self,
filter,
update,
projection=None,
sort=None,
upsert=False,
return_document=ReturnDocument.BEFORE,
session=None,
**kwargs
):
"""
Find and update a document atomically.
Parameters:
- filter: query criteria
- update: update specification
- projection: fields to return
- sort: sort specification
- upsert: insert if no match found
- return_document: return original or modified document
- bypass_document_validation: skip validation
- max_time_ms: maximum execution time
- session: optional ClientSession
Returns:
Original or modified document
"""Navigate and process query results with cursors.
class Cursor:
def __iter__(self):
"""Return cursor iterator."""
def __next__(self):
"""Get next document."""
def next(self):
"""Get next document (Python 2 compatibility)."""
def limit(self, limit):
"""
Limit number of results.
Parameters:
- limit: maximum number of documents
Returns:
Cursor instance (chainable)
"""
def skip(self, skip):
"""
Skip number of documents.
Parameters:
- skip: number of documents to skip
Returns:
Cursor instance (chainable)
"""
def sort(self, key_or_list, direction=1):
"""
Sort results.
Parameters:
- key_or_list: field name or list of (key, direction) pairs
- direction: 1 for ascending, -1 for descending
Returns:
Cursor instance (chainable)
"""
def batch_size(self, batch_size):
"""
Set cursor batch size.
Parameters:
- batch_size: number of documents per batch
Returns:
Cursor instance (chainable)
"""
def close(self):
"""Close the cursor."""
@property
def alive(self):
"""
Check if cursor is still alive.
Returns:
bool: True if cursor has more results
"""
def count(self, with_limit_and_skip=False):
"""
Count documents (deprecated - use count_documents).
Parameters:
- with_limit_and_skip: apply limit/skip to count
Returns:
int: Document count
"""from pymongo import MongoClient
client = MongoClient()
db = client.mydb
collection = db.mycollection
# Insert documents
doc = {"name": "Alice", "age": 30}
result = collection.insert_one(doc)
print(f"Inserted: {result.inserted_id}")
docs = [
{"name": "Bob", "age": 25},
{"name": "Charlie", "age": 35}
]
result = collection.insert_many(docs)
print(f"Inserted: {result.inserted_ids}")
# Find documents
doc = collection.find_one({"name": "Alice"})
print(f"Found: {doc}")
for doc in collection.find({"age": {"$gte": 30}}):
print(f"Adult: {doc}")
# Update documents
result = collection.update_one(
{"name": "Alice"},
{"$set": {"age": 31}}
)
print(f"Modified: {result.modified_count}")
# Delete documents
result = collection.delete_one({"name": "Alice"})
print(f"Deleted: {result.deleted_count}")from pymongo import ASCENDING, DESCENDING
# Query with cursor operations
cursor = collection.find({"age": {"$lt": 50}}) \
.sort([("age", ASCENDING), ("name", DESCENDING)]) \
.skip(10) \
.limit(5)
for doc in cursor:
print(doc)
# Get distinct values
ages = collection.distinct("age")
print(f"Distinct ages: {ages}")from pymongo import ReturnDocument
# Find and update atomically
updated_doc = collection.find_one_and_update(
{"name": "Alice"},
{"$inc": {"age": 1}},
return_document=ReturnDocument.AFTER
)
print(f"Updated document: {updated_doc}")
# Find and delete atomically
deleted_doc = collection.find_one_and_delete({"name": "Bob"})
print(f"Deleted document: {deleted_doc}")Install with Tessl CLI
npx tessl i tessl/pypi-pymongo