Fake pymongo stub for testing simple MongoDB-dependent code
—
Index management operations including creation, deletion, and inspection of indexes with support for compound indexes, text indexes, and index options. Indexes improve query performance and enforce constraints.
Create single and compound indexes with various options and configurations.
def create_index(self, key_or_list, cache_for=300, session=None, **kwargs):
"""
Create an index on the collection.
Parameters:
- key_or_list: str or list, index key specification
- cache_for: int, index cache duration (ignored)
- session: ClientSession, session to use (ignored)
- **kwargs: index options (unique, sparse, etc.)
Returns:
str: index name
Raises:
OperationFailure: if index creation fails
"""
def create_indexes(self, indexes, session=None):
"""
Create multiple indexes.
Parameters:
- indexes: list, list of IndexModel instances or index specifications
- session: ClientSession, session to use (ignored)
Returns:
list: list of created index names
Raises:
OperationFailure: if index creation fails
"""Usage Example:
from mongomock import ASCENDING, DESCENDING
collection = mongomock.MongoClient().db.users
# Create single field index
index_name = collection.create_index('email')
# Create index with direction
index_name = collection.create_index([('age', ASCENDING)])
# Create compound index
index_name = collection.create_index([
('status', ASCENDING),
('created_at', DESCENDING)
])
# Create unique index
index_name = collection.create_index('username', unique=True)
# Create sparse index (only indexes documents with the field)
index_name = collection.create_index('phone', sparse=True)
# Create index with custom name
index_name = collection.create_index('email', name='email_unique_idx')
# Create multiple indexes at once
indexes = [
[('name', ASCENDING)],
[('age', ASCENDING), ('status', ASCENDING)],
[('created_at', DESCENDING)]
]
index_names = collection.create_indexes(indexes)List and examine existing indexes on collections.
def list_indexes(self, session=None):
"""
List all indexes on the collection.
Parameters:
- session: ClientSession, session to use (ignored)
Returns:
CommandCursor: cursor over index information documents
"""
def index_information(self, session=None):
"""
Get detailed information about all indexes.
Parameters:
- session: ClientSession, session to use (ignored)
Returns:
dict: mapping of index names to index information
"""Usage Example:
collection = mongomock.MongoClient().db.users
# List all indexes
indexes_cursor = collection.list_indexes()
for index in indexes_cursor:
print(f"Index: {index['name']}, Key: {index['key']}")
# Get index information dictionary
index_info = collection.index_information()
for name, info in index_info.items():
print(f"Index {name}: {info}")
# Check if specific index exists
if 'email_1' in index_info:
print("Email index exists")Remove indexes from collections to free resources or modify index strategy.
def drop_index(self, index_or_name, session=None):
"""
Drop a single index.
Parameters:
- index_or_name: str or list, index name or key specification
- session: ClientSession, session to use (ignored)
Returns:
None
Raises:
OperationFailure: if index doesn't exist or drop fails
"""
def drop_indexes(self, session=None):
"""
Drop all indexes except the default _id index.
Parameters:
- session: ClientSession, session to use (ignored)
Returns:
None
Raises:
OperationFailure: if drop operation fails
"""Usage Example:
collection = mongomock.MongoClient().db.users
# Drop index by name
collection.drop_index('email_1')
# Drop index by key specification
collection.drop_index([('age', 1)])
# Drop all indexes (except _id)
collection.drop_indexes()
# Handle errors
try:
collection.drop_index('nonexistent_index')
except mongomock.OperationFailure as e:
print(f"Index drop failed: {e}")Support for various MongoDB index types and configuration options.
Single Field Indexes:
# Basic single field index
collection.create_index('field_name')
# Single field with direction
collection.create_index([('field_name', DESCENDING)])Compound Indexes:
# Multiple field index
collection.create_index([
('field1', ASCENDING),
('field2', DESCENDING),
('field3', ASCENDING)
])Index Options:
# Unique constraint
collection.create_index('email', unique=True)
# Sparse index (only documents with the field)
collection.create_index('optional_field', sparse=True)
# Partial index with filter
collection.create_index('status', partialFilterExpression={
'status': {'$in': ['active', 'pending']}
})
# TTL index (time-to-live)
collection.create_index('expiry_date', expireAfterSeconds=3600)
# Case-insensitive index
collection.create_index('name', collation={
'locale': 'en_US',
'strength': 2
})Usage Example:
collection = mongomock.MongoClient().db.users
# Create various index types
collection.create_index('email', unique=True, sparse=True)
collection.create_index([
('department', ASCENDING),
('hire_date', DESCENDING)
], name='dept_hire_idx')
# TTL index for session cleanup
collection.create_index('last_access', expireAfterSeconds=1800)
# Partial index for active users only
collection.create_index('performance_score',
partialFilterExpression={'status': 'active'})Understand index impact on query performance and storage.
Query Optimization:
collection = mongomock.MongoClient().db.users
# Index supports efficient queries
collection.create_index([('status', 1), ('created_at', -1)])
# Efficient query (uses index)
recent_active = collection.find({
'status': 'active',
'created_at': {'$gte': datetime(2023, 1, 1)}
}).sort('created_at', -1)
# Index prefix usage
status_query = collection.find({'status': 'active'}) # Uses index prefixIndex Maintenance:
# Monitor index usage
index_stats = collection.index_information()
for name, info in index_stats.items():
print(f"Index {name} has key: {info.get('key')}")
# Rebuild indexes if needed
collection.drop_indexes()
collection.create_index([('status', 1), ('created_at', -1)])Control index naming and organize index strategy.
# Index naming patterns
def gen_index_name(index_list):
"""
Generate index name from key specification.
Parameters:
- index_list: list, list of (key, direction) tuples
Returns:
str: generated index name
"""Usage Example:
from mongomock.helpers import gen_index_name
# Automatic name generation
index_spec = [('email', 1), ('status', 1)]
auto_name = gen_index_name(index_spec) # 'email_1_status_1'
# Custom index names
collection.create_index('email', name='users_email_unique')
collection.create_index([('dept', 1), ('role', 1)], name='dept_role_idx')
# Descriptive naming convention
collection.create_index('created_at', name='users_created_desc',
background=True)# Helper functions for index management
def create_index_list(key_or_list, direction=None):
"""
Create standardized index specification.
Parameters:
- key_or_list: str or list, index key specification
- direction: int, default direction for string keys
Returns:
list: standardized list of (key, direction) tuples
"""Usage Example:
from mongomock.helpers import create_index_list
# Convert various formats to standard format
spec1 = create_index_list('email') # [('email', 1)]
spec2 = create_index_list('age', -1) # [('age', -1)]
spec3 = create_index_list([('name', 1), ('age', -1)]) # unchanged
# Use in index operations
for spec in [spec1, spec2, spec3]:
index_name = collection.create_index(spec)
print(f"Created index: {index_name}")# Sort/Index directions
ASCENDING = 1
DESCENDING = -1
# Index types (for documentation)
TEXT = 'text'
GEOSPHERE = '2dsphere'
HASHED = 'hashed'Install with Tessl CLI
npx tessl i tessl/pypi-mongomock