collMod validator usage in python

I am trying to provide data validation on existing collection. For this, i am using “collMod” command in python as below:

options = dict(containing $jsonschema validator)
db.command("collMod", "collection_name", options)

i am verifying whether this latest validator is updated or not in “collection_name” as below:

db.command("listCollections")

But i am not able to see updated validator $jsonschema.

Note: I am able to update using mongo shell. However, i have to do with python only.

I require your help!!

Best Regards,
M Jagadeesh

Hi @Manepalli_Jagadeesh - good question!

When calling the command function, additional arguments must be passed as keyword arguments. You’ve provided options as a positional argument, which doesn’t work.

The following works for me:

db.command('collMod', 'a_simple_collection', validator={
    '$jsonSchema': {
         'bsonType': "object",
         'properties': {
            'name': {
               'bsonType': "string",
            },
         }
    }
})

You can see that although the validator data is a dict, I’m providing it as the validator keyword arg with validator=.

If you are building up your ‘collMod’ arguments in a dict , such as:

options = {
    'validator': {
        '$jsonSchema': {
             'bsonType': "object",
             'properties': {
                'name': {
                   'bsonType': "string",
                },
             },
        },
    }
}

You could then provide this to command with the ** syntax, which expands a dictionaries keys and values into keyword arguments, like this:

db.command('collMod', 'a_simple_collection', **options)

(But I think providing your validator as a single keyword argument is a better idea.)

I hope this helps. Let me know if you have any more questions!

3 Likes

Hi @Mark_Smith,
Thank you for clear explanation with provided example. Now, i am able to see modified validator $jsonschema.

2 Likes

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