I am trying to add a validator to a MongoDB collection using pymongo.
The command I would like to run adapted from here
Is equivalent to this:
db.runCommand( {
collMod: "contacts",
validator: { phone: { $type: 'string' } },
validationLevel: "moderate"
} )
{ "ok" : 1 }
And subsequently will throw an error if a non-string datatype is inserted tin the phone field
Using python I did the following:
db.command({'collMod': 'contacts',
'validator': {'phone': {'$type': 'string'}},
'validationLevel': 'moderate'})
.
.
.
InvalidDocument: Cannot encode object: Collection(Database(MongoClient(host=['localhost:27017'], document_class=dict, tz_aware=False, connect=True), 'test_table'), 'contacts')
I'm sure that my python interpretation is wrong, that much is clear, however I have not been able to find the correct translation, or whether this is even possible in python
I eventually found the solution here. Hopefully it can help someone else.
Of course, when all else fails read the docs...
Also valid is an
OrderedDict
EDIT:
Current Documentation from where the above comes from. Note this was added after the question was originally answered so the documentation has changed, however it should still be relevant