【问题标题】:Does Pymongo have validation rules built in?Pymongo 是否内置了验证规则?
【发布时间】:2018-03-16 02:34:04
【问题描述】:

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

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

【问题讨论】:

  • 仅供参考:使用 pymongo 读取验证规则:db.get_collection('test').options().get('validator')

标签: mongodb validation pymongo


【解决方案1】:

MongoDB 支持引擎级别的文档验证,因此您可以通过 pymongo 获取它。您向引擎声明您的“模式”(实际上是规则)。这是一个很好的起点:https://docs.mongodb.com/manual/core/document-validation/

【讨论】:

  • 你说对了一部分。 MongoDB 提供内置验证,但不幸的是,pymongo 的文档中没有说明验证
  • 任何人都可以为此添加示例吗?我真的很挣扎!
  • 是的,这就是我一直在寻找的,但我只是使用 mongo 引擎 ORM 解决了它
【解决方案2】:

python 驱动程序文档确实对如何使用db.command 有所了解。这是一个完整的工作示例:

    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"
                }
             }
      }
    }
    
    # Per the docs, args to command() require that the first kev/value pair
    # be the command string and its principal argument, followed by other
    # arguments.  There are two ways to do this:  Using an OrderDict:
    cmd = OrderedDict([('collMod', 'myColl'),
            ('validator', vexpr),
            ('validationLevel', 'moderate')]
    db.command(cmd)
    
    # Or, use the kwargs construct:
    # db.command('collMod','myColl', validator=vexpr, validationLevel='moderate')

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

【讨论】:

    【解决方案3】:

    您可以为您的文档验证架构创建一个单独的 JSON 文件,如下所示:

        {
          "collMod": "users",
          "validator": {
            "$jsonSchema": {
              "bsonType": "object",
              "required": ["email", "password","name"],
              "properties": {
                "email": {
                  "bsonType": "string",
                  "description": "Correo Electrónico"
                },
                "password": {
                  "bsonType": "string",
                  "description": "Una representación Hash de la contraseña"
                },
                "name": {
                  "bsonType": "object",
                  "required": ["first", "last"],
                  "description": "Objeto que separa los nombres y apellidos",
                  "properties":  {
                    "first": {
                      "bsonType": "string",
                      "description": "Primer y segundo nombre"
                    },
                    "last": {
                      "bsonType": "string",
                      "description": "Primer y segundo apellido"
                    }
                  }
                },
              }
            }
          }
        }
    

    然后就可以在python脚本中使用了,例如:

    from pymongo import MongoClient
    import json #parse JSON  file as dict
    from collections import OrderedDict #preserve the order (key, value) in the gived insertions on the dict
    
    client = MongoClient("your_mongo_uri")
    db = client.your_db_name 
    
    with open('your_schema_file.json', 'r') as j:
        d = json.loads(j.read())
    
    d = OrderedDict(d)
    
    db.command(d)
    

    OrderedDict Info

    collMod Info

    Schema Validation Info

    【讨论】:

      猜你喜欢
      • 2015-04-30
      • 2011-10-25
      • 1970-01-01
      • 1970-01-01
      • 2019-12-10
      • 2020-10-12
      • 2021-01-11
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多