Skip to main content

Logo





Mongomantic = Pymongo + Pydantic

Mongomantic is a lightweight python MongoDB ORM based on Pydantic and PyMongo, heavily inspired by Mongoengine.

API

from mongomantic import BaseRepository, MongoDBModel, connect

connect("localhost:27017", "test_db")  # Setup mongodb connection

class User(MongoDBModel):
    first_name: str
    last_name: str

class UserRepository(BaseRepository):

    class Meta:  # Required internal class
        model = User  # Define model type
        collection = "user"  # Define collection name


user = User(first_name="John", last_name="Smith")

user = UserRepository.save(user)  # PyMongo wrapping classmethods
user.id  # ObjectId that was saved

Usage

pip install mongomantic

Connection to MongoDB

To connect to your database, a connect function similar to mongoengine is provided.

from mongomantic import connect

connect("localhost:27017", "test_db")  # Setup mongodb connection

Repository Usage

The BaseRepository class wraps around MongoDBModel, providing functions to save models into a collection, retrieve models, create indexes, and use the aggregation pipeline syntax on the collection.

To implement a new repository, you must first inherit from BaseRepository and provide an internal Meta class to specify the model and collection being used.

class UserRepository(BaseRepository):
    class Meta:
        model = User
        collection = "user"

And that's it! You can now access repository CRUD operations and more. More details found in the Repositories guide.

Adding indexes is simple using the Mongomantic Index model:

class UserRepository(BaseRepository):
    class Meta:
        model = User
        collection = "user"
        indexes = [
            Index(fields=["+first_name"]),
            Index(fields=["+first_name", "-last_name"], unique=True)
        ]

Safe Repository

For production use, you can either handle the errors thrown by BaseRepository in case of errors on your own, or you can use SafeRepository which handles all the errors for you and logs them, while returning meaningful safe values like None and []. Usage is exactly similar to using BaseRepository.

from mongomantic import SafeRepository, MongoDBModel, connect

connect("localhost:27017", "test_db")  # Setup mongodb connection

class User(MongoDBModel):
    first_name: str
    last_name: str

class UserRepository(SafeRepository):

    class Meta:  # Required internal class
        model = User  # Define model type
        collection = "user"  # Define collection name

user = UserRepository.get(id="123")  # DoesNotExist error handled

assert user is None

Similar to this example, all other errors are handled.

Your Opinion is Needed

Mongomantic can be kept as a simple wrapper around PyMongo, or developed into a miniature version of Mongoengine that's built on Pydantic. The first direction would result in the following API:

# Direct pymongo wrapper
users = UserRepository.find({"$and": [{"age": {"$gt": 12}}, {"name": "John"}]})

# But matches can be done as keyword arguments
john = UserRepository.find(name="John")

On the other hand, a more complex version of Mongomantic could lead to:

# More Pythonic way of writing queries
users = UserRepository.find(User.age > 12, name="John")

# Matches still compact
john = UserRepository.find(name="John")

Please submit your vote below.

Simple PyMongo Wrapper - Prefer speed and native mongodb filters More Complex Wrapper - Pythonic Filters

🚀 TODO

  • Documentation
  • Basic API similar to mongoengine, without any queryset logic
  • Built on Pydantic models, no other schema required
  • BaseRepository responsible for all operations (instead of the model itself)
  • SafeRepository derived from BaseRepository with all errors handled
  • Repository/model plugin framework (ex. SyncablePlugin, TimestampedPlugin, etc.)
  • Wrapper for aggregation pipelines
  • Mongomock tests
  • Flexible connect() function wrapper around PyMongo client (aliases, replica sets, retry writes, etc.)
  • Clean up imports and expose essentials in main file

🛡 License

License

This project is licensed under the terms of the MIT license. See LICENSE for more details.

📃 Citation

@misc{mongomantic,
  author = {mongomantic},
  title = {A MongoDB Python ORM, built on Pydantic and PyMongo.},
  year = {2021},
  publisher = {GitHub},
  journal = {GitHub repository},
  howpublished = {\url{https://github.com/RamiAwar/mongomantic}}
}

Credits

This project was generated with python-package-template.

Metadata

Release files for mongomantic 0.4.2

For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.

Source distribution (sdist)

Source distribution for mongomantic 0.4.2
File Size Uploaded
mongomantic-0.4.2.tar.gz 13.0 kB Details

Built distribution (wheel)

Table of built distributions (wheels) for mongomantic 0.4.2
File Interpreter ABI Platform
mongomantic-0.4.2-py3-none-any.whl Python 3 none any Details

Total release size: 25.0 kB

Release files / mongomantic-0.4.2.tar.gz

Download URL mongomantic-0.4.2.tar.gz
Size 13.0 kB
Tags Source
SHA-256 checksum
How to use checksums
8f51a7768bdde997207e3efabb03f79c45d9497c906582463feb59251e415c23
BLAKE2b-256 checksum
How to use checksums
1343122b9bdf92a236453aeee0236aafb1135a411ab9d40e7bcf16ff4b8d3ce1
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via poetry/1.1.5 CPython/3.9.2 Darwin/20.3.0

Release files / mongomantic-0.4.2-py3-none-any.whl

Download URL mongomantic-0.4.2-py3-none-any.whl
Size 12.1 kB
Tags Python 3
SHA-256 checksum
How to use checksums
5c39f01d26ba75aef2f43e21be7e921d50525a9e8a5b9045e741c2824a0cc44f
BLAKE2b-256 checksum
How to use checksums
44ab7e85a29776e965fcd1873c4e509c65359ca0a972beec228aa1aea1189a90
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via poetry/1.1.5 CPython/3.9.2 Darwin/20.3.0

Release history Release notifications | RSS feed

This release

0.4.2 This release

2 release files

0.4.1

2 release files

0.4.0

2 release files

0.3.1

2 release files

0.3.0

2 release files

0.2.1

2 release files

0.2.0

2 release files

Anthropic, PBC Visionary sponsor Bloomberg Visionary sponsor Hudson River Trading Visionary sponsor Meta Visionary sponsor NVIDIA Visionary sponsor Microsoft Sustainability sponsor Depot Continuous Integration AWS Cloud computing and Security Sponsor Datadog Monitoring Fastly CDN Google Download Analytics Sentry Error logging StatusPage Status page