{"id":2593,"library":"mongomock","title":"Mongomock","description":"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.","status":"active","version":"4.3.0","language":"en","source_language":"en","source_url":"https://github.com/mongomock/mongomock","tags":["testing","mocking","mongodb","database","pymongo"],"install":[{"cmd":"pip install mongomock","lang":"bash","label":"Install with pip"}],"dependencies":[{"reason":"Mongomock 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.","package":"pymongo","optional":true}],"imports":[{"note":"The primary way to instantiate a mock MongoDB client.","symbol":"MongoClient","correct":"import mongomock\nclient = mongomock.MongoClient()"},{"note":"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.","symbol":"patch","correct":"from mongomock import patch\n@patch(servers=(('server.example.com', 27017),))"}],"quickstart":{"code":"import mongomock\n\n# 1. Create a mock client instance\nclient = mongomock.MongoClient()\n\n# 2. Access a database (it's created on first access)\ndb = client.mydatabase\n\n# 3. Access a collection\ncollection = db.mycollection\n\n# 4. Perform common MongoDB operations\n# Insert documents\ninsert_result_one = collection.insert_one({\"name\": \"Alice\", \"age\": 30})\nprint(f\"Inserted one: {insert_result_one.inserted_id}\")\n\ninsert_result_many = collection.insert_many([{\"name\": \"Bob\", \"age\": 25}, {\"name\": \"Charlie\", \"age\": 35}])\nprint(f\"Inserted many IDs: {insert_result_many.inserted_ids}\")\n\n# Find documents\nalice = collection.find_one({\"name\": \"Alice\"})\nprint(f\"Found Alice: {alice}\")\n\nall_docs = list(collection.find({}))\nprint(f\"All documents: {all_docs}\")\n\n# Update documents\nupdate_result = collection.update_one({\"name\": \"Bob\"}, {\"$set\": {\"age\": 26, \"city\": \"New York\"}})\nprint(f\"Matched {update_result.matched_count}, modified {update_result.modified_count} for Bob\")\n\nbob = collection.find_one({\"name\": \"Bob\"})\nprint(f\"Updated Bob: {bob}\")\n\n# Delete documents\ndelete_result = collection.delete_one({\"name\": \"Charlie\"})\nprint(f\"Deleted count for Charlie: {delete_result.deleted_count}\")\n\ncharlie = collection.find_one({\"name\": \"Charlie\"})\nprint(f\"Found Charlie (should be None): {charlie}\") # Output: Found Charlie (should be None): None\n\n# The database and its collections are in-memory and reset with a new MongoClient instance.","lang":"python","description":"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."},"warnings":[{"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).","message":"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.","severity":"breaking","affected_versions":"4.0.0 and above"},{"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.","message":"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.","severity":"gotcha","affected_versions":"All versions"},{"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.","message":"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.","severity":"gotcha","affected_versions":"All versions"},{"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.","message":"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.","severity":"gotcha","affected_versions":"All versions"}],"env_vars":null,"last_verified":"2026-04-10T00:00:00.000Z","next_check":"2026-07-09T00:00:00.000Z"}