ObjectIdAnnotation

class pydantic_mongo.ObjectIdAnnotation[source]

Bases: object

A Pydantic annotation for MongoDB ObjectId fields.

This annotation provides validation and serialization for MongoDB ObjectId fields in Pydantic models. It allows ObjectIds to be:

  • Created from string representations

  • Validated for correct ObjectId format

  • Serialized to string format for JSON output

Example

from typing_extensions import Annotated
from bson import ObjectId
from pydantic import BaseModel
from pydantic_mongo import ObjectIdAnnotation

class User(BaseModel):
    # Using the annotation directly
    id: Annotated[ObjectId, ObjectIdAnnotation]

    # Or using the provided type alias
    id: PydanticObjectId  # equivalent to above

When the model is loaded, strings will be automatically converted to ObjectId instances if they are valid, and an error will be raised if they are not. When the model is serialized to JSON, ObjectIds will be converted to strings.

classmethod validate(value)[source]

Validate and convert a string to ObjectId.

Parameters:

value – The string value to validate and convert

Returns:

The converted ObjectId instance

Return type:

ObjectId

Raises:

ValueError – If the value is not a valid ObjectId string