使用pymongo将验证器添加到Mongodb集合中 [英] Add a validator to a Mongodb collection with pymongo

查看:98
本文介绍了使用pymongo将验证器添加到Mongodb集合中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用pymongo将验证器添加到MongoDB集合中.

I am trying to add a validator to a MongoDB collection using pymongo.

我要运行的命令改编自此处

The command I would like to run adapted from here

等效于此:

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

使用python,我执行了以下操作:

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')

我确定我的python解释是错误的,很明显,但是我无法找到正确的翻译,或者甚至在python中也可能实现

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...

..注意:: command文档中的键顺序为 重要的(动词"必须放在首位),因此命令 需要多个键(例如findandmodify) 应该使用:class:~bson.son.SON的实例,或者 一个字符串和kwargs而不是Python dict

.. 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

OrderedDict

query = [('collMod', 'contacts'),
        ('validator', {'phone': {'$type': 'string'}}),
        ('validationLevel', 'moderate')]
query = OrderedDict(query)
db.command(query)
{'ok': 1.0}

当前文档来自于何处.请注意,此内容是在最初回答问题后添加的,因此文档已更改,但是仍然应该相关

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

这篇关于使用pymongo将验证器添加到Mongodb集合中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆