Registry / database / mongomock

mongomock

JSON →
library4.3.0pypypi✓ verified 24d ago

Mongomock is a small, in-memory library that provides a fake PyMongo stub for testing Python code that interacts with MongoDB. It aims to mimic the behavior of the official PyMongo driver as closely as possible, allowing for database-dependent code to be tested without needing a running MongoDB instance. It is actively maintained, with the current version being 4.3.0, and receives regular updates to support new PyMongo and MongoDB features.

pip install mongomock
INSTALL
IMPORT
SIG · MONGOMOCK
M
mongomock
databasepythonv4.3.0
Install
1.9s avg
Import
471ms
Disk
20MB
Pass rate
10/ 10
Env Coverage10 / 10
glibc
3.93.13
musl
3.93.13
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
musl
py 3.103.95 runs
installs and imports cleanly · install 0.0s · import 0.508s · 22.1MB
glibc
py 3.103.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.
Debug
Known issues
breakingMongomock v4.0.0 dropped support for Python 2. Additionally, its behavior adapted to align with PyMongo v4's API changes. If your project uses PyMongo v3 or Python 2, you may encounter compatibility issues or changed behavior.
fix
Ensure your project runs on Python 3 and, if using PyMongo, upgrade to PyMongo v4 or newer if possible. If not, use an older version of mongomock compatible with your PyMongo version (e.g., mongomock < 4.0.0 for PyMongo v3).
affects: 4.0.0 and above
gotchaMongomock is a mock library, not a full MongoDB server. It aims for reasonable completeness but does not implement all MongoDB features or edge-case behaviors perfectly. Unsupported operations may raise `NotImplementedError` or behave differently than a real MongoDB instance. Advanced aggregation pipelines, geospatial queries, or complex indexing behaviors might not be fully replicated.
fix
Always check for `NotImplementedError` during testing if using advanced MongoDB features. For critical functionality, consider integration tests against a real MongoDB instance. Review mongomock's documentation or source for supported features.
affects: All versions
gotchaPerformance of `mongomock` can be significantly slower than a real MongoDB, especially for bulk write operations or operations involving unique constraints on large datasets. This is due to its in-memory, Pythonic implementation of database logic.
fix
When testing performance-critical code paths, be aware that `mongomock` might introduce artificial bottlenecks. Optimize test data size where possible. For actual performance benchmarking, use a real MongoDB instance.
affects: All versions
gotchaWhen dynamically patching `pymongo.MongoClient` in complex applications (e.g., Flask), ensure you patch the `MongoClient` class in the module where it is actually imported and used by your application logic, rather than just where it's defined. Python's import caching can lead to the original object still being referenced elsewhere.
fix
Use `mongomock.patch` decorator or `unittest.mock.patch.object` on the `MongoClient` instance or the module that imports it within your tests. Verify that the patched client is indeed being used by your application code during testing.
affects: All versions
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.
fix
Refactor 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.
fix
Downgrade 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.
fix
Instead 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.
fix
Upgrade 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.
Agent activity
3 hits · last 30 days
node
2
Resources
mongomock — pip install mongomock · libregistry