Is there a way to add objects that we do not define in the schema to the database using pymongo?

I want to add objects that I don’t define in the schema to my database.

from pymongo import MongoClient
from collections import OrderedDict
import sys

def create_collection(coll_name):
    db = MongoClient('mongodb://localhost:27017/')['dbname']
    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('collectionname')
    

What if I wanted to add :

db.dbname.insertOne({name: "Jason", status:"updated"})

I know ı can add this to schema but is there a way to do this with python and pymongo. How can ı add name and status to my schema using python and pymongo.

Altering a collection’s validator does not seem to be supported by any public API.

1 Like

Do you know about Javascript? Just like python, it is not a strongly-typed language, and its object format allows to add-remove properties and methods to object freely. JSON is the serialized version of this object system, and you can do the same with it: add anything you want.

MongoDB follows this JS/JSON freedom extending some more types and saving the file as binary making the BSON type.

adding the types and schemas to this freedom is mainly for other languages’ expectations to have a defined shape like from a relational database. you do not need them unless you want strict rules.

so your schema here in python, you can say, is extracting data in a defined shape and easily validating data with that shape.

you can at any time start using schemaless free-style for reading/inserting/removing data that does not conform to a shape, less or more data. Although not difficult in python, it will be your responsibility to validate and convert data without a schema.

as for using this in python with pymongo, just know that the method names follow snake case, where words are connected with underscore: “insertOne” becomes “insert_one”. check pymongo documentation for more verbs.

1 Like

Welcome to the MongoDB community @Furkan_Arslan!

Schema validation is optional in MongoDB and you can choose a validationLevel for how strictly documents are validated.

However, in your example validation you have set additionalProperties:true so should already be able to add fields that are not part of your declared schema validation. Fields names/paths that match your schema rules will still be validated, but additionalProperties:true does not validate properties that aren’t listed.

If you do have strict validation enabled, there is also the option for database users with the bypassDocumentValidation permission to bypass validation per operation. In PyMongo this can be set with a bypass_document_validation boolean parameter for supported operations.

@Jack_Woehr You can add or update the JSON Schema validator for an existing collection using the collMod command: Add Document Validation to an Existing Collection. Validator updates only apply to future inserts or updates (existing documents are unaffected).

Regards,
Stennie

4 Likes

True dat, @Stennie , but I didn’t find an exposed API to do this in pymongo, which was the original question.

1 Like

Hi @Jack_Woehr,

Modifying the validator wouldn’t be needed for the original question because it already allows additionalProperties.

However, the collMod command can be invoked from PyMongo using db.command() similar to this example: collMod validator usage in python - #2 by Mark_Smith

Regards,
Stennie

TIL !! Thanks, @Stennie

1 Like

This topic was automatically closed 5 days after the last reply. New replies are no longer allowed.