Mongomock
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.
Warnings
- breaking Mongomock 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.
- gotcha Mongomock 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.
- gotcha Performance 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.
- gotcha When 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.
Install
-
pip install mongomock
Imports
- MongoClient
import mongomock client = mongomock.MongoClient()
- patch
from mongomock import patch @patch(servers=(('server.example.com', 27017),))
Quickstart
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.