DEV.co
Open-Source Testing · mongomock

mongomock

Mongomock is a Python library that provides an in-memory mock of MongoDB collections for unit testing without requiring a real MongoDB instance. It mimics pymongo's API so tests can run quickly and reliably in isolation.

Source: GitHub — github.com/mongomock/mongomock
1k
GitHub stars
358
Forks
Python
Primary language
ISC
License (OSI-approved)

Key facts

Objective fields from the source. Values we can't verify are shown as “Unknown” rather than guessed.

FieldValue
Repositorymongomock/mongomock
Ownermongomock
Primary languagePython
LicenseISC — OSI-approved
Stars1k
Forks358
Open issues184
Latest release4.3.0 (2024-11-19)
Last updated2025-06-30
Sourcehttps://github.com/mongomock/mongomock

What mongomock is

Mongomock implements a behavioral mock of MongoDB's pymongo client and collection objects, storing data in-memory and supporting common operations (insert, find, update, delete) with MongoDB query semantics. It can patch pymongo imports at test time to transparently replace real connections with mocked ones.

Quickstart

Get the mongomock source

Clone the repository and explore it locally.

terminalbash
git clone https://github.com/mongomock/mongomock.gitcd mongomock# follow the project's README for install & configuration

Need it deployed, integrated, or customized instead? DEV.co ships production installs.

Best use cases

Unit testing pymongo-dependent code

Test Python code that uses pymongo without spinning up MongoDB infrastructure, eliminating setup/teardown overhead and enabling fast, isolated test runs in CI/CD pipelines.

Testing MongoDB migration from pymongo v3 to v4

Use mongomock v4+ to validate code compatibility with pymongo v4 API changes before deploying to production, as mongomock adapts its behavior to the installed pymongo version.

Local development and rapid iteration

Develop and test MongoDB-using features on laptops or restricted environments (e.g., air-gapped machines) where running a real MongoDB instance is impractical.

Implementation considerations

  • Mongomock requires pymongo to be installed; it does not provide standalone mocking of MongoDB wire protocol.
  • Test code must use pymongo.MongoClient() constructor rather than from pymongo import MongoClient to allow mongomock.patch() decorator to intercept connections.
  • Unimplemented MongoDB features will raise NotImplementedError rather than silently succeed; review your code's query and operation usage against mongomock's capabilities.
  • In-memory storage means tests cannot validate disk-level concerns (e.g., index persistence, journaling) or performance characteristics of on-disk operations.
  • Use mongomock.utcnow() helper for time-dependent tests to enable consistent mocking of 'now' across test suites.

When to avoid it — and what to weigh

  • Integration testing against real MongoDB — If your test suite must validate behavior against actual MongoDB instances (e.g., testing replication, sharding, or version-specific behaviors), mongomock's in-memory simulation will not suffice.
  • Production use or data persistence — Mongomock is strictly for testing; it stores data only in memory and provides no durability, replication, or production-grade reliability guarantees.
  • Advanced MongoDB features — Mongomock does not stub unimplemented features; it raises NotImplementedError for unsupported pymongo operations (e.g., transactions, aggregation pipeline stages, or geospatial queries), so test code relying on these will fail.
  • Exact behavioral fidelity across MongoDB versions — Mongomock aims for reasonable completeness, not a perfect replica. Corner cases and edge case behaviors may differ from the real MongoDB; this is acceptable for unit tests but not integration tests.

License & commercial use

Mongomock is licensed under the ISC License, a permissive open-source license that permits use, modification, and distribution in both commercial and non-commercial projects with minimal restrictions (requires retention of license and copyright notices).

ISC License permits commercial use and modification. However, this is a unit-testing library; verify your organization's policy on using open-source test dependencies in production environments. No commercial support or indemnification is provided by the project.

DEV.co evaluation signals

Editorial assessment — not user reviews. Directional, with an explicit confidence level.

SignalAssessment
MaintenanceActive
DocumentationAdequate
License clarityClear
Deployment complexityLow
DEV.co fitStrong
Assessment confidenceHigh
Security considerations

Mongomock is intended for test environments only and should never be used in production. It provides no authentication, encryption, access control, or audit logging. Use only in isolated test suites; do not expose mongomock instances to untrusted networks. No security vulnerabilities are claimed in available data, but the project's maintainer-seeking status suggests limited security review capacity.

Alternatives to consider

MongoDB Community Edition (local or Docker)

Provides real MongoDB behavior with full feature support; better for integration tests or when exact behavioral fidelity is critical. Requires infrastructure setup and increases test runtime.

unittest.mock / pytest fixtures with testcontainers-mongodb

Enables isolated real MongoDB instances per test via Docker; offers true behavior validation at the cost of test speed and complexity. Suitable for integration test suites.

moto (AWS mocking library with DocumentDB support)

If using AWS DocumentDB, moto provides mock DocumentDB behaviors. Mongomock is more direct for pymongo-only use cases.

Software development agency

Build on mongomock with DEV.co software developers

Mongomock eliminates MongoDB setup overhead during unit testing. Integrate it into your test suite today to speed up CI/CD pipelines and improve developer velocity.

Talk to DEV.co

Related open-source tools

Surfaced by semantic similarity across the DEV.co open-source index.

Related on DEV.co

Explore the category and the services that help you build with it.

mongomock FAQ

Does mongomock support MongoDB transactions?
Not currently. Transactions are listed as a feature unlikely to be implemented soon due to MongoDB's complexity. If your code uses transactions, tests will raise NotImplementedError; consider mocking at a higher level or using real MongoDB for integration tests.
Can I use mongomock with async pymongo?
Unknown. The README does not document async support. Review mongomock's source or issue tracker to determine whether async/await is mocked; if not, consider alternatives like pytest-asyncio with testcontainers.
How do I test code that creates MongoDB connections internally?
Use the @mongomock.patch(servers=...) decorator to intercept pymongo.MongoClient() calls. Ensure your code uses pymongo.MongoClient() directly rather than 'from pymongo import MongoClient' for patching to work.
Is mongomock suitable for testing aggregation pipelines?
Partially. Mongomock implements basic aggregation stages but does not claim full support. Review the README and test suite to confirm your specific pipeline stages are supported; unsupported stages will raise NotImplementedError.

Work with a software development agency

Adopting mongomock is usually one piece of a larger software development effort. As a software development agency, DEV.co provides software development services and web development expertise — pairing senior software developers and web developers with your team to design, build, and operate open-source testing software in production.

Mock MongoDB in Your Tests—Without the Infrastructure

Mongomock eliminates MongoDB setup overhead during unit testing. Integrate it into your test suite today to speed up CI/CD pipelines and improve developer velocity.