Pydantic Mongo
raw JSON → 3.1.0 verified Mon Apr 27 auth: no python
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 Common errors
error ImportError: cannot import name 'ObjectIdField' from 'pydantic_mongo' ↓
cause 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.
error AttributeError: 'str' object has no attribute 'insert_one' ↓
cause 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(...).
error TypeError: ObjectIdField only supports assigning ObjectId or strictly string typed values, not <class 'NoneType'> ↓
cause 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.
error pydantic_core._pydantic_core.ValidationError: 1 validation error for User id ↓
cause 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.
Warnings
breaking In 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).
gotcha Pydantic 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.
gotcha You 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).
Imports
- ObjectIdField wrong
from pydantic.fields import ObjectIdcorrectfrom pydantic_mongo import ObjectIdField - AbstractRepository wrong
from pydantic_mongo.repository import AbstractRepositorycorrectfrom pydantic_mongo import AbstractRepository - AsyncAbstractRepository
from pydantic_mongo import AsyncAbstractRepository
Quickstart
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}')