Skip to main content

mongo-validations-generator

mongo-validations-generator is a lightweight Python library for generating MongoDB JSON Schema validation rules using standard Python type annotations and Pydantic models.

It allows you to define your MongoDB collection schemas declaratively with Python classes, while supporting advanced typing features like Annotated, Literal, Union, custom validation markers, and nested models.


Features

  • ✅ Auto-generates $jsonSchema validation for MongoDB
  • ✅ Support for Python type hints: str, int, float, bool, list, None
  • ✅ Nested objects using Pydantic-style inheritance
  • ✅ Annotated constraints using Annotated[..., Len(...)]
  • ✅ Support for Union, Optional, and Literal types
  • ✅ Custom BSON type markers (e.g., Long)
  • ✅ Ability to ignore fields with SchemaIgnored

🚀 Getting Started

1. Define a model

from annotated_types import Len
from mongo_validations_generator import MongoValidator, Long, SchemaIgnored
from typing import Annotated, Literal

class Product(MongoValidator):
    name: str
    description: str
    categories: list[str]
    price: Annotated[int, Long]
    tags: Annotated[list[str], Len(1)]
    internal_code: Annotated[str, SchemaIgnored]
    status: Literal["active", "archived"]

2. Generate the schema

import json

print(json.dumps(Product.generate_validation_rules("Product"), indent=2))

output:

{
  "$jsonSchema": {
    "title": "Product Validation",
    "bsonType": "object",
    "required": [
      "name",
      "description",
      "categories",
      "price",
      "tags",
      "status"
    ],
    "properties": {
      "name": {
        "bsonType": "string",
        "description": "'name' must match schema"
      },
      "description": {
        "bsonType": "string",
        "description": "'description' must match schema"
      },
      "categories": {
        "bsonType": "array",
        "items": {
          "bsonType": "string"
        },
        "description": "'categories' must match schema"
      },
      "price": {
        "bsonType": "long",
        "description": "'price' must match schema"
      },
      "tags": {
        "bsonType": "array",
        "items": {
          "bsonType": "string"
        },
        "minItems": 1,
        "description": "'tags' must match schema"
      },
      "status": {
        "enum": ["active", "archived"],
        "bsonType": "string",
        "description": "'status' must match schema"
      }
    }
  }
}

📦 Supported BSON Types

The following BSON types are currently supported by the schema generator:

Python Type BSON Type Notes
str "string"
int "int"
float "double"
bool "bool"
list[...] "array" Supports nested items, constraints, and unions
None / Optional[...] "null" Supports Union[Type, None] and Optional[...]
Annotated[int, Long] "long" Use Annotated[int, Long] to convert to "long"
Literal[...] "enum" Will emit enum values and infer BSON type if homogeneous
Enum / StrEnum / IntEnum "enum" Maps to the BSON enum validator using the enum's members
MongoValidator subclass "object" Nested objects are fully supported
Annotated[list[T], Len(...)] "array" Adds minItems and maxItems constraints to list validation
BSONDecimal128 "decimal" Outputs a decimal-compatible field using MongoDB's Decimal128 format

❗ Not supported: dict, set, tuple, frozenset, or other complex built-in containers.

Metadata

Release files for mongo-validations-generator 1.2.0

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

Source distribution (sdist)

Source distribution for mongo-validations-generator 1.2.0
File Size Uploaded
mongo_validations_generator-1.2.0.tar.gz 28.7 kB Details

Built distribution (wheel)

Table of built distributions (wheels) for mongo-validations-generator 1.2.0
File Interpreter ABI Platform
mongo_validations_generator-1.2.0-py3-none-any.whl Python 3 none any Details

Total release size: 39.7 kB

Release files / mongo_validations_generator-1.2.0.tar.gz

Download URL mongo_validations_generator-1.2.0.tar.gz
Size 28.7 kB
Tags Source
SHA-256 checksum
How to use checksums
6033990dc8b1ac23fe3e8d320b9e70f3e327b5e8729d65835c6a11befdbad574
BLAKE2b-256 checksum
How to use checksums
035468db87b622b9d92bd82f40890f2a5fec9ddceeac8a3ad686e875966a3716
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
Yes
Uploaded via uv/0.8.12

Release files / mongo_validations_generator-1.2.0-py3-none-any.whl

Download URL mongo_validations_generator-1.2.0-py3-none-any.whl
Size 11.0 kB
Tags Python 3
SHA-256 checksum
How to use checksums
d4bede5fbadcb18d139953ddde49590ef033104948daf2573ae361cfaf483458
BLAKE2b-256 checksum
How to use checksums
98c95a7838ebb8b46819ea1cf8529b05b1e894006a7d98f62072622602f8c07c
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
Yes
Uploaded via uv/0.8.12

Release history Release notifications | RSS feed

This release

1.2.0 This release

2 release files

1.1.0

2 release files

1.0.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