gpt4 book ai didi

mongodb - Pymongo 是否内置了验证规则?

转载 作者:行者123 更新时间:2023-12-03 18:38:02 25 4
gpt4 key购买 nike

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

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

最佳答案

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"
}
}
}
}

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

关于mongodb - Pymongo 是否内置了验证规则?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46569262/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com