Pymongo 是否内置了验证规则? [英] Does Pymongo have validation rules built in?

查看:45
本文介绍了Pymongo 是否内置了验证规则?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试根据架构验证插入的文档,并试图找到一种方法来验证插入的文档.

I am trying to validate an inserted document against a schema, and was trying to find a way to validate the inserted document.

有像 MongoEngine 这样的库说他们可以完成这项工作,但是有没有办法直接通过 pymongo 进行文档验证?

There are libraries like MongoEngine that say they do the work, but is there a way to do document validation directly via pymongo ?

推荐答案

python 驱动程序文档确实对如何使用 db.command 做了一些说明.这是一个完整的工作示例:

The python driver docs are indeed a little light on how to use the db.command. Here is a complete working example:

    from pymongo import MongoClient
    from collections import OrderedDict
    import sys
    
    client = MongoClient()   # supply connection args as appropriate 
    db = client.testX
    
    db.myColl.drop()
    
    db.create_collection("myColl")  # Force create!
    
    #  $jsonSchema expression type is prefered.  New since v3.6 (2017):
    vexpr = {"$jsonSchema":
      {
             "bsonType": "object",
             "required": [ "name", "year", "major", "gpa" ],
             "properties": {
                "name": {
                   "bsonType": "string",
                   "description": "must be a string and is required"
                },
                "gender": {
                   "bsonType": "string",
                   "description": "must be a string and is not required"
                },
                "year": {
                   "bsonType": "int",
                   "minimum": 2017,
                   "maximum": 3017,
                   "exclusiveMaximum": False,
                   "description": "must be an integer in [ 2017, 3017 ] and is required"
                },
                "major": {
                   "enum": [ "Math", "English", "Computer Science", "History", None ],
                   "description": "can only be one of the enum values and is required"
                },
                "gpa": {
                   # In case you might want to allow doubles OR int, then add
                   # "int" to the bsonType array below:
                   "bsonType": [ "double" ],
                   "minimum": 0,
                   "description": "must be a double and is required"
                }
             }
      }
    }
    
    cmd = OrderedDict([('collMod', 'myColl'),
            ('validator', vexpr),
            ('validationLevel', 'moderate')])
    
    db.command(cmd)
    
    try:
        db.myColl.insert({"x":1})
        print "NOT good; the insert above should have failed."
    except:
        print "OK. Expected exception:", sys.exc_info()    
    
    try:
        okdoc = {"name":"buzz", "year":2019, "major":"Math", "gpa":3.8}
        db.myColl.insert(okdoc)
        print "All good."
    except:
        print "exc:", sys.exc_info()    

这篇关于Pymongo 是否内置了验证规则?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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