Add a validator to a Mongodb collection with pymon

2020-06-19 08:47发布

问题:

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

回答1:

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 Python dict

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