{"id":3002,"library":"mongoengine","title":"MongoEngine","description":"MongoEngine is a Python Object-Document Mapper (ODM) for working with MongoDB. It provides a declarative schema definition, query builder, and features like document relationships, inheritance, and validation, making it easier to interact with MongoDB databases using Python objects. The library is actively maintained, with regular updates to support new PyMongo versions and introduce features, currently at version 0.29.3.","status":"active","version":"0.29.3","language":"en","source_language":"en","source_url":"https://github.com/MongoEngine/mongoengine","tags":["ODM","MongoDB","database","NoSQL"],"install":[{"cmd":"pip install mongoengine","lang":"bash","label":"Install latest version"}],"dependencies":[{"reason":"Official MongoDB Python driver; MongoEngine builds on top of it for database interaction.","package":"pymongo","optional":false}],"imports":[{"symbol":"Document","correct":"from mongoengine import Document"},{"symbol":"StringField","correct":"from mongoengine import StringField"},{"symbol":"connect","correct":"from mongoengine import connect"},{"note":"As of v0.27.0, ValidationError moved from the top-level `mongoengine` module to `mongoengine.errors`.","wrong":"from mongoengine import ValidationError","symbol":"ValidationError","correct":"from mongoengine.errors import ValidationError"}],"quickstart":{"code":"import os\nfrom mongoengine import Document, StringField, connect\n\n# Connect to MongoDB (replace with your connection string)\n# Use os.environ.get for secure, flexible credentials\nmongo_uri = os.environ.get('MONGO_URI', 'mongodb://localhost:27017/testdb')\nconnect(alias='default', host=mongo_uri)\n\nclass User(Document):\n    name = StringField(required=True, max_length=50)\n    email = StringField(required=True, unique=True)\n\n    meta = {'collection': 'users'}\n\n# Create a new user\nuser = User(name='Alice Wonderland', email='alice@example.com')\nuser.save()\nprint(f\"Saved user: {user.name} with ID: {user.id}\")\n\n# Find a user by email\nalice = User.objects(email='alice@example.com').first()\nif alice:\n    print(f\"Found user: {alice.name}\")\n\n# Update a user\nalice.name = 'Alice W.'\nalice.save()\nprint(f\"Updated user: {alice.name}\")\n\n# Delete a user\nalice.delete()\nprint(f\"User '{alice.email}' deleted.\")\n\n# Clean up (optional: disconnect)\n# disconnect_all() # Or use disconnect('default')\n","lang":"python","description":"This quickstart demonstrates defining a `Document` model, connecting to a MongoDB instance, creating, saving, finding, updating, and deleting documents. It highlights the use of `StringField` and basic query operations with `User.objects`."},"warnings":[{"fix":"Review the official release notes for v0.20.0 (and subsequent major versions like 0.25.0, 0.27.0) and update your models and queries accordingly. Pay close attention to `ReferenceField` definitions and `ObjectId` comparisons.","message":"Major changes were introduced in v0.20.0, especially regarding how `ObjectId` instances are handled and the default behavior of `ReferenceField`. For example, `ReferenceField.db_field` was renamed to `reverse_delete_rule`.","severity":"breaking","affected_versions":">=0.20.0"},{"fix":"Always install `mongoengine` and let it pull its compatible `pymongo` version. If you need a specific `pymongo` version, check MongoEngine's `setup.py` or release notes for tested compatibility. For example, v0.29.1 added support for `pymongo` 4.9.","message":"MongoEngine's compatibility with `pymongo` is crucial. Newer versions of MongoEngine often require specific `pymongo` versions, and upgrading `pymongo` independently can lead to issues.","severity":"breaking","affected_versions":"All versions, especially when upgrading either library."},{"fix":"Use `connect(alias='my_db_alias', host='...')` and specify the alias in `Document.meta = {'db_alias': 'my_db_alias'}` or when querying/saving documents.","message":"The `connect` function takes an `alias` parameter which defaults to 'default'. When managing multiple database connections, explicitly provide unique aliases to prevent conflicts and ensure operations are directed to the correct database.","severity":"gotcha","affected_versions":"All versions"},{"fix":"Be mindful of how `id` fields are managed. For new documents, ensure the `id` field is not set before the first `save()`. To force an insert or update, consider using `insert()` or `update()` methods explicitly if your use case requires it, or `update_one()` with `upsert=True`.","message":"`Document.save()` performs both inserts and updates. If a document has an `id` (or `_id`) field, `save()` will attempt an update; otherwise, it will perform an insert. This can lead to unexpected updates if an `id` is accidentally set before the first save, or new documents not being inserted if an existing ID is reused.","severity":"gotcha","affected_versions":"All versions"}],"env_vars":null,"last_verified":"2026-04-11T00:00:00.000Z","next_check":"2026-07-10T00:00:00.000Z"}