Yash Singh
Yash Singh

Reputation: 31

How to create schema in MongoDB using python?

I'm fairly new to MongoDB. I'll try my best to summarize the problem at hand here. I've been provided three different JSON schemas and i want to create this schemas in MongoDB using python. My code is as follows:

import pymongo

client = pymongo.MongoClient("mongodb://127.0.0.1:27017/")

mydb=client['UserDetails']

information = mydb.Userinformation

user_schema = {

    'firstName': {
        'type': 'string',
        'minlength': 1,
        'required': True,
        'coerce': str.capitalize
    },
    'lastName': {
        'type': 'string',
        'minlength': 1,
        'required': True,
        'coerce': str.capitalize
    },
    'email': {
        'type': 'string',
        "required": False,
        "coerce": str,
        "nullable": True
    },
    'phoneNo': {
        'type': 'integer',
        'required': True,
        'unique': True
    },
    'userId': {
        'type': 'integer',
        'required': True,
        'unique': True
    },
    'patientId': {
        'type': 'integer',
        'required': True,
        'unique': True
    },
    'age': {
        'type': 'integer'
    },
    "userStatus": {
        "type": "integer",
        "nullable": True
    }
}

information.insert_many(user_schema)

The above code line gives me an error as below

TypeError: document must be an instance of dict, bson.son.SON, bson.raw_bson.RawBSONDocument, or a type that inherits from collections.MutableMapping

information.insert_one(user_schema)

And trying this gives me an error

cannot encode object: method 'capitalize' of 'str' objects, of type: class 'method_descriptor'

Any help how to create this schema in mongoDB using python will be much appreciated!

Upvotes: 3

Views: 18715

Answers (1)

Belly Buster
Belly Buster

Reputation: 8814

MongoDB uses a JSON schema of BSON types; your schema doesn't match the spec.

There's no concept of "coerce" and uniqueness is handled through unique indexes.

I've got you started with this code snippet that gets you some of the way there, but this is a lot of your own research you will need to do.

from pymongo import MongoClient
from pymongo.errors import CollectionInvalid
from collections import OrderedDict

db = MongoClient("mongodb://localhost:27019/")['mydatabase']

user_schema = {
    'firstName': {
        'type': 'string',
        'minlength': 1,
        'required': True,
    },
    'lastName': {
        'type': 'string',
        'minlength': 1,
        'required': True,
    },
    'email': {
        'type': 'string',
        "required": False,
    },
    'phoneNo': {
        'type': 'int',
        'required': True,
    },
    'userId': {
        'type': 'int',
        'required': True,
    },
    'patientId': {
        'type': 'int',
        'required': True,
    },
    'age': {
        'type': 'int'
    },
    "userStatus": {
        "type": "int"
    }
}

collection = 'Userinformation'
validator = {'$jsonSchema': {'bsonType': 'object', 'properties': {}}}
required = []

for field_key in user_schema:
    field = user_schema[field_key]
    properties = {'bsonType': field['type']}
    minimum = field.get('minlength')

    if type(minimum) == int:
        properties['minimum'] = minimum

    if field.get('required') is True: required.append(field_key)

    validator['$jsonSchema']['properties'][field_key] = properties

if len(required) > 0:
    validator['$jsonSchema']['required'] = required

query = [('collMod', collection),
         ('validator', validator)]

try:
    db.create_collection(collection)
except CollectionInvalid:
    pass

command_result = db.command(OrderedDict(query))

Upvotes: 6

Related Questions