Defining data schema using pymongo

Here is a code sample using pymongo to create a new collection with a jsonschema:

from pymongo import MongoClient


def create_collection(coll_name):
    client = MongoClient('mongodb://localhost:27017/')
    db = client.test
    result = db.create_collection(coll_name, validator={
        '$jsonSchema': {
            'bsonType': 'object',
            'additionalProperties': True,
            'required': ['component', 'path'],
            'properties': {
                'component': {
                    'bsonType': 'string'
                },
                'path': {
                    'bsonType': 'string',
                    'description': 'Set to default value'
                }
            }
        }
    })

    print(result)


if __name__ == '__main__':
    create_collection('my_coll')

As you can see in this screenshot, I got the correct jsonschema in my MDB server:

3 Likes