使用pymongo将验证器添加到Mongodb集合中

编程入门 行业动态 更新时间:2024-10-15 08:22:40
本文介绍了使用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:

dbmand({'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) dbmand(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集合中

本文发布于:2023-11-22 14:29:01,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1617810.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:pymongo   Mongodb

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!