MongoDB

MongoRunner is the built-in NoSQLRunner implementation for MongoDB. It uses pymongo under the hood and exposes only read-only operations.

Connect

from mango.integrations.mongodb import MongoRunner

db = MongoRunner()
db.connect("mongodb://localhost:27017/mydb")

The database name must be part of the URI. Mango calls get_default_database() to extract it.

Connection string formats

# Local
db.connect("mongodb://localhost:27017/mydb")

# With auth
db.connect("mongodb://user:password@localhost:27017/mydb")

# MongoDB Atlas
db.connect("mongodb+srv://user:password@cluster.mongodb.net/mydb")

# With options
db.connect(
    "mongodb://localhost:27017/mydb",
    serverSelectionTimeoutMS=5000,
    connectTimeoutMS=10000,
)

Any extra kwargs are passed directly to MongoClient.

Allowed operations

MongoRunner.execute_query() only accepts these operations:

OperationDescription
findFilter, project, sort, limit
aggregateFull aggregation pipeline
countcount_documents() with optional filter
distinctDistinct values for a field

Any other operation raises ValidationError before hitting the database.

Methods

All methods inherited from NoSQLRunner:

# Execute a query
result: pd.DataFrame = db.execute_query(QueryRequest(
    operation="count",
    collection="users",
    filter={"active": True},
))

# List collections
collections: list[str] = db.list_collections()

# Get schema for all collections
schema: dict[str, SchemaInfo] = db.introspect_schema()

# Sample documents
docs: list[dict] = db.get_sample_documents("orders", n=5)

# Index info
indexes: list[dict] = db.get_indexes("orders")

Error handling

All MongoDB errors are wrapped in Mango's exception hierarchy:

ExceptionWhen raised
BackendErrorConnection failure, collection not found
QueryErrorMongoDB error during query execution
ValidationErrorOperation not in allowlist, missing required field