Mongomock

4.3.0 · active · verified Fri Apr 10

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

Install

Imports

Quickstart

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.

view raw JSON →