Install & Compatibility
Where this runs
tested against v4.3.0 · pip install
no network on importno background threads
Install × environment matrix
Each cell = how many times install + import succeeded across repeated harness runs. Partial = flaky.
glibc = Debian/Ubuntu slim · musl = Alpine Linux
muslpy 3.10–3.95 runs
installs and imports cleanly · install 0.0s · import 0.508s · 22.1MB
glibcpy 3.10–3.95 runs
installs and imports cleanly · install 1.9s · import 0.434s · 23MB
20MB installed
● package 20MB
Code
Verified usage
Verified import paths — ran on the pinned version, not inferred.
MongoClient
✓ import mongomock
client = mongomock.MongoClient()
The primary way to instantiate a mock MongoDB client.
patch
✓ from mongomock import patch
@patch(servers=(('server.example.com', 27017),))
A decorator for patching `pymongo.MongoClient` calls within a test function, redirecting them to a mongomock client. It's crucial to patch at the point where `pymongo.MongoClient` is looked up, not necessarily defined, due to Python's import mechanisms.
This quickstart demonstrates how to initialize a `mongomock.MongoClient`, interact with a database and collection, and perform basic CRUD (Create, Read, Update, Delete) operations, mimicking the PyMongo API. The data is stored entirely in memory and is transient for each client instance.
import mongomock
# 1. Create a mock client instance
client = mongomock.MongoClient()
# 2. Access a database (it's created on first access)
db = client.mydatabase
# 3. Access a collection
collection = db.mycollection
# 4. Perform common MongoDB operations
# Insert documents
insert_result_one = collection.insert_one({"name": "Alice", "age": 30})
print(f"Inserted one: {insert_result_one.inserted_id}")
insert_result_many = collection.insert_many([{"name": "Bob", "age": 25}, {"name": "Charlie", "age": 35}])
print(f"Inserted many IDs: {insert_result_many.inserted_ids}")
# Find documents
alice = collection.find_one({"name": "Alice"})
print(f"Found Alice: {alice}")
all_docs = list(collection.find({}))
print(f"All documents: {all_docs}")
# Update documents
update_result = collection.update_one({"name": "Bob"}, {"$set": {"age": 26, "city": "New York"}})
print(f"Matched {update_result.matched_count}, modified {update_result.modified_count} for Bob")
bob = collection.find_one({"name": "Bob"})
print(f"Updated Bob: {bob}")
# Delete documents
delete_result = collection.delete_one({"name": "Charlie"})
print(f"Deleted count for Charlie: {delete_result.deleted_count}")
charlie = collection.find_one({"name": "Charlie"})
print(f"Found Charlie (should be None): {charlie}") # Output: Found Charlie (should be None): None
# The database and its collections are in-memory and reset with a new MongoClient instance.
Errors
Common errors & fixes
NotImplementedError: Although '$lookup' is a valid operator for the aggregation pipeline, it is currently not implemented in Mongomock.
Mongomock aims for a reasonably complete mock of MongoDB but does not implement all advanced aggregation pipeline operators, leading to this error when using unsupported features like $lookup, $sum (in older versions), $dateSubtract, or $getField.
fixRefactor your test code to avoid the unsupported aggregation operator, mock the specific aggregation call at a higher level (e.g., `collection.aggregate.return_value`), or upgrade `mongomock` to a version that may have added support for the operator.
TypeError: BulkOperationBuilder.add_update() got an unexpected keyword argument 'sort'
This error occurs due to an incompatibility between `mongomock` and newer versions of PyMongo (e.g., 4.11+). PyMongo introduced a `sort` keyword argument to `BulkOperationBuilder.add_update()`, which `mongomock` did not expect.
fixDowngrade your PyMongo dependency to a version compatible with your `mongomock` installation (e.g., `pip install 'pymongo<4.11'`) or upgrade `mongomock` to a version that explicitly supports the new PyMongo API.
AttributeError: 'CommandCursor' object has no attribute 'to_list'
While PyMongo's `CommandCursor` object provides a `to_list()` method, `mongomock`'s mock cursor may not implement this specific utility method, resulting in an AttributeError.
fixInstead of calling `.to_list()` on the cursor, convert it to a list using the standard Python `list()` constructor, like `list(aggregation_cursor)`, which is compatible with both `pymongo` and `mongomock`.
ModuleNotFoundError: No module named 'importlib.metadata'
This error arises when using newer `mongomock` versions (e.g., 4.2.0.post1 or later) with older Python environments (specifically Python 3.7 or earlier), because `mongomock` started relying on `importlib.metadata`, a module introduced in Python 3.8.
fixUpgrade your Python environment to version 3.8 or newer, or downgrade `mongomock` to a version compatible with your current Python version (e.g., `pip install 'mongomock<4.2.0'`).
Upgrade
Version history
4.3.0latest on PyPI · released Nov 16, 2024
Audit
Dependencies
pymongooptionalMongomock is designed to emulate the PyMongo API. While not a hard dependency for mongomock itself, the library's behavior and API compatibility (especially since v4.0.0) adapt to the version of PyMongo installed in your test environment. Applications being tested will typically depend on PyMongo.