Fake pymongo stub for testing simple MongoDB-dependent code
—
Database-level operations including collection management, database commands, and configuration. The Database class provides the interface for working with MongoDB databases in mongomock.
Access collections within the database with support for configuration options and dynamic collection creation.
def get_collection(self, name, codec_options=None, read_preference=None,
write_concern=None, read_concern=None):
"""
Get a collection instance.
Parameters:
- name: str, collection name
- codec_options: CodecOptions, encoding/decoding options
- read_preference: ReadPreference, read preference override
- write_concern: WriteConcern, write concern override
- read_concern: ReadConcern, read concern override
Returns:
Collection instance
"""Usage Example:
client = mongomock.MongoClient()
db = client.testdb
# Get collection by name
collection = db.get_collection('users')
collection = db['users'] # Alternative syntax
collection = db.users # Alternative syntax
# Get collection with custom options
from mongomock import WriteConcern, CodecOptions
collection = db.get_collection('users',
write_concern=WriteConcern(w=1),
codec_options=CodecOptions(tz_aware=True)
)Create, list, drop, and rename collections within the database.
def list_collection_names(self, filter=None, session=None):
"""
List all collection names in the database.
Parameters:
- filter: dict, filter criteria for collections
- session: ClientSession, session to use (ignored)
Returns:
List[str]: list of collection names
"""
def list_collections(self, filter=None, session=None, nameOnly=False):
"""
List collections in the database with full metadata.
Parameters:
- filter: dict, filter criteria for collections
- session: ClientSession, session to use (ignored)
- nameOnly: bool, return names only if True
Returns:
CommandCursor: cursor over collection information documents
"""
def collection_names(self, include_system_collections=True, session=None):
"""
Get collection names (deprecated, use list_collection_names).
Parameters:
- include_system_collections: bool, include system collections
- session: ClientSession, session to use (ignored)
Returns:
List[str]: list of collection names
Deprecated:
Use list_collection_names() instead
"""
def create_collection(self, name, **kwargs):
"""
Create a new collection.
Parameters:
- name: str, collection name
- **kwargs: collection creation options
Returns:
Collection instance
Raises:
CollectionInvalid: if collection already exists or invalid name
"""
def drop_collection(self, name_or_collection, session=None):
"""
Drop a collection from the database.
Parameters:
- name_or_collection: str or Collection, collection name or instance
- session: ClientSession, session to use (ignored)
Returns:
None
"""
def rename_collection(self, name, new_name, dropTarget=False):
"""
Rename a collection.
Parameters:
- name: str, current collection name
- new_name: str, new collection name
- dropTarget: bool, drop target collection if exists
Returns:
None
Raises:
OperationFailure: if operation fails
"""Usage Example:
db = mongomock.MongoClient().testdb
# List collections
collections = db.list_collection_names()
print(f"Collections: {collections}")
# Create collection explicitly
users_col = db.create_collection('users')
# Drop collection
db.drop_collection('users')
# or
db.drop_collection(users_col)
# Rename collection
db.create_collection('old_name')
db.rename_collection('old_name', 'new_name')Execute database-level commands and administrative operations.
def command(self, command, **kwargs):
"""
Execute a database command.
Parameters:
- command: str or dict, command to execute
- **kwargs: additional command parameters
Returns:
Dict[str, Any]: command result
Raises:
OperationFailure: if command fails
"""Usage Example:
db = mongomock.MongoClient().testdb
# Execute database commands
result = db.command('dbStats')
result = db.command({'collStats': 'users'})
# List collections via command
result = db.command('listCollections')Resolve database references to actual documents.
def dereference(self, dbref, session=None):
"""
Dereference a DBRef to get the referenced document.
Parameters:
- dbref: DBRef, database reference to resolve
- session: ClientSession, session to use (ignored)
Returns:
Dict[str, Any] or None: referenced document or None if not found
"""Usage Example:
from bson import DBRef, ObjectId
db = mongomock.MongoClient().testdb
# Create a reference
ref = DBRef('users', ObjectId())
# Dereference
document = db.dereference(ref)Create database instances with different configuration options.
def with_options(self, codec_options=None, read_preference=None,
write_concern=None, read_concern=None):
"""
Create a new Database instance with different options.
Parameters:
- codec_options: CodecOptions, encoding/decoding options
- read_preference: ReadPreference, read preference setting
- write_concern: WriteConcern, write concern setting
- read_concern: ReadConcern, read concern setting
Returns:
Database: new database instance with updated options
"""Usage Example:
from mongomock import WriteConcern, ReadConcern, CodecOptions
db = mongomock.MongoClient().testdb
# Create database with custom options
custom_db = db.with_options(
write_concern=WriteConcern(w=1),
read_concern=ReadConcern(level='majority'),
codec_options=CodecOptions(tz_aware=True)
)Access database configuration and metadata.
@property
def name(self):
"""str: database name"""
@property
def client(self):
"""MongoClient: client instance that created this database"""
@property
def read_preference(self):
"""ReadPreference: current read preference"""
@property
def codec_options(self):
"""CodecOptions: current codec options"""
@property
def read_concern(self):
"""ReadConcern: current read concern"""Usage Example:
client = mongomock.MongoClient()
db = client.testdb
print(f"Database name: {db.name}")
print(f"Client: {db.client}")
print(f"Read preference: {db.read_preference}")
print(f"Codec options: {db.codec_options}")class Database:
def __init__(self, client, name, _store, read_preference=None,
codec_options=None, read_concern=None):
"""
Create a Database instance.
Note: Databases are typically created via MongoClient.get_database()
rather than direct instantiation.
Parameters:
- client: MongoClient, parent client instance
- name: str, database name
- _store: Store, internal storage backend
- read_preference: ReadPreference, read preference setting
- codec_options: CodecOptions, codec options
- read_concern: ReadConcern, read concern setting
"""Install with Tessl CLI
npx tessl i tessl/pypi-mongomock