Skip to content

mongomock-ng

PyPI version CI License Codecov

In-memory MongoDB mock for Python testing. Drop-in replacement for pymongo in tests — no MongoDB server required.

Quick Start

pip install mongomock-ng
import mongomock_ng as mongomock

client = mongomock.MongoClient()
db = client['test_db']
collection = db['test_collection']
collection.insert_one({'name': 'test', 'value': 42})
print(collection.find_one())

Why mongomock-ng?

Testing code that interacts with MongoDB typically requires either a real instance (high maintenance, CI overhead) or hand-crafted mocks (fragile, violates DRY). mongomock-ng provides a third option: an in-memory mock that behaves like real MongoDB.

def increase_votes(collection):
    collection.update_many({}, {'$inc': {'votes': 1}})

def test_increase_votes():
    collection = mongomock.MongoClient().db.collection
    collection.insert_many([{'votes': 1}, {'votes': 2}])
    increase_votes(collection)
    for doc in collection.find():
        assert doc['votes'] >= 2

Features

  • CRUD operations: insert, find, update, delete — full pymongo API
  • Query operators: $gt, $in, $regex, $exists, and more
  • Aggregation pipeline: $match, $group, $lookup, $project, 30+ stages
  • Geospatial queries: $geoIntersects, $geoWithin, $near, $geoNear
  • Sessions & transactions: ClientSession with snapshot isolation
  • Index support: unique, sparse, TTL, compound, 2dsphere
  • Query profiler: capture queries, analyze index coverage
  • Document validation: $jsonSchema validator support

Examples

Example scripts are in the examples/ directory:

Patching pymongo

If your code creates the connection itself, use mongomock_ng.patch:

@mongomock_ng.patch(servers=(('server.example.com', 27017),))
def test_increase_votes_endpoint():
    client = pymongo.MongoClient('server.example.com')
    client.db.collection.insert_many([{'votes': 1}])
    call_endpoint('/votes')
    # verify client.db.collection

Acknowledgements

Originally developed by Rotem Yaari, then by Martin Domke, then Pascal Corpet. Currently maintained by Pascal Corpet, Felipe Monteiro Jácome. Fork maintained by Felipe Monteiro Jácome.