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...
.. note:: the order of keys in the
command
document is significant (the "verb" must come first), so commands which require multiple keys (e.g.findandmodify
) should use an instance of :class:~bson.son.SON
or a string and kwargs instead of a Pythondict
Also valid is an OrderedDict
query = [('collMod', 'contacts'),
('validator', {'phone': {'$type': 'string'}}),
('validationLevel', 'moderate')]
query = OrderedDict(query)
db.command(query)
{'ok': 1.0}
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With