Registry / database / pydantic-mongo

pydantic-mongo

JSON →
library3.1.0pypypi✓ verified 87d ago

A document object mapper (ODM) for Pydantic and PyMongo, allowing you to define MongoDB document schemas with Pydantic models and perform CRUD operations with an optional repository pattern. Current version: 3.1.0 (released 2025-04-18). Active development with frequent minor releases.

pip install pydantic-mongo
INSTALL
IMPORT
SIG · PYDANTIC-MONGO
P
pydantic-mongo
databasepythonv3.1.0
Install
4.4s avg
Import
709ms
Disk
36MB
Pass rate
10/ 10
Env Coverage10 / 10
glibc
3.93.13
musl
3.93.13
Install & Compatibility
Where this runs
tested against v3.1.0 · pip install
no network on importno background threads
Install × environment matrix
Each cell = how many times install + import succeeded across repeated harness runs. Partial = flaky.
glibc = Debian/Ubuntu slim · musl = Alpine Linux
musl
py 3.103.95 runs
installs and imports cleanly · install 0.0s · import 0.738s · 36MB
glibc
py 3.103.95 runs
installs and imports cleanly · install 4.4s · import 0.680s · 37MB
36MB installed
● package 36MB
Code
Verified usage

Verified import paths — ran on the pinned version, not inferred.

ObjectIdField
from pydantic_mongo import ObjectIdField
from pydantic.fields import ObjectId
ObjectIdField is a custom field type provided by pydantic-mongo, not Pydantic's ObjectId.
AbstractRepository
from pydantic_mongo import AbstractRepository
from pydantic_mongo.repository import AbstractRepository
AbstractRepository is exported at the package level since v2.4.0.
AsyncAbstractRepository
from pydantic_mongo import AsyncAbstractRepository
Introduced in v2.4.0.

Basic usage: define a Pydantic model, connect to MongoDB, and insert a document.

import os from pydantic import BaseModel from pydantic_mongo import PydanticMongo class User(BaseModel): name: str email: str mongo = PydanticMongo(connection_string=os.environ.get('MONGO_URI', 'mongodb://localhost:27017')) db = mongo.get_database('myapp') collection = mongo.get_collection('users', model=User) user = User(name='John', email='john@example.com') inserted_id = collection.insert_one(user) print(f'Inserted user with id: {inserted_id}')
Debug
Known issues
breakingIn v3.0.0, ObjectId serialization changed to return a string instead of an ObjectId instance. This affects how ObjectIdField values are returned from queries and must be handled when comparing IDs or passing to functions expecting ObjectId.
fix
Upgrade to v3.x and update any code that relied on ObjectId being returned as an ObjectId object. Use pymongo's ObjectId constructor if needed: from bson import ObjectId; ObjectId(str_id).
affects: >=3.0.0
gotchaPydantic v2 vs v1: pydantic-mongo is built on Pydantic v2. If you use Pydantic v1 models, you may encounter validation errors or compatibility issues.
fix
Use Pydantic v2 models (from pydantic import BaseModel). If you must use v1, stick with pydantic-mongo <2.0.0.
affects: >=2.0.0
gotchaYou must pass the model class to get_collection() when using custom Pydantic models; otherwise, the collection operates on raw dicts.
fix
Always call mongo.get_collection('collection_name', model=MyModel).
affects: all
Errors
Common errors & fixes
ImportError: cannot import name 'ObjectIdField' from 'pydantic_mongo'
Outdated version (<2.0.0) or incorrect import path.
fix
Upgrade to latest version with pip install --upgrade pydantic-mongo and use the correct import: from pydantic_mongo import ObjectIdField.
AttributeError: 'str' object has no attribute 'insert_one'
get_collection() was called with a collection name as a plain string instead of the actual collection object.
fix
Assign the result of get_collection() to a variable: collection = mongo.get_collection(...).
TypeError: ObjectIdField only supports assigning ObjectId or strictly string typed values, not <class 'NoneType'>
Setting an ObjectIdField to None. ObjectIdField does not allow None by default.
fix
Define the field with ObjectIdField(default=None) or use Optional[ObjectIdField] to allow null values.
pydantic_core._pydantic_core.ValidationError: 1 validation error for User id
ObjectIdField is required but not provided when creating a new model. ObjectIdField is automatically generated by the library, but if you set it manually to an invalid value, validation fails.
fix
Let the library auto-generate IDs. If you must set it manually, ensure it is a valid ObjectId string or ObjectId instance. For new documents, omit the id field entirely.
Upgrade
Version history
3.1.0latest on PyPI · released Apr 18, 2025
Audit
Dependencies
pydanticrequiredCore dependency for model definition
pymongorequiredMongoDB driver
Agent activity
5 hits · last 30 days
node
4
Resources
pydantic-mongo — pip install pydantic-mongo · libregistry