PyMongo In-Memory

0.5.0 · active · verified Thu Apr 16

PyMongo In-Memory is a Python library that provides an ephemeral in-memory MongoDB server, primarily designed for testing and continuous integration environments. It achieves this by downloading and running a real `mongod` binary configured to use the in-memory storage engine. The library is actively maintained, with frequent updates that include support for newer MongoDB versions and bug fixes, typically released every few months.

Common errors

Warnings

Install

Imports

Quickstart

This quickstart demonstrates how to use `pymongo-inmemory.MongoClient` within a context manager. The server is automatically started upon entering the `with` block and stopped upon exiting. Basic CRUD operations are shown, connecting to a 'testdb' database and a 'test_collection'. You can specify the MongoDB version via environment variables or `setup.cfg`.

import os
from pymongo_inmemory import MongoClient

# Configure MongoDB version via environment variable for consistency
os.environ['PYMONGOIM__MONGO_VERSION'] = os.environ.get('PYMONGOIM__MONGO_VERSION', '6.0')

with MongoClient() as client:
    db = client['testdb']
    collection = db['test_collection']

    # Insert a document
    doc = {"name": "Alice", "age": 30}
    insert_result = collection.insert_one(doc)
    print(f"Inserted document with ID: {insert_result.inserted_id}")

    # Find a document
    found_doc = collection.find_one({"name": "Alice"})
    print(f"Found document: {found_doc}")

    # Update a document
    collection.update_one({"name": "Alice"}, {"$set": {"age": 31}})
    updated_doc = collection.find_one({"name": "Alice"})
    print(f"Updated document: {updated_doc}")

    # Delete a document
    collection.delete_one({"name": "Alice"})
    remaining_doc = collection.find_one({"name": "Alice"})
    print(f"Remaining document: {remaining_doc}")

print("In-memory MongoDB server automatically stopped.")

view raw JSON →