【发布时间】:2020-10-09 08:18:32
【问题描述】:
我正在使用mongodb 和PyMongo,我想将架构定义与应用程序的其余部分分开。我有文件 user_schema.jsonwith 用于 user 集合的架构:
{
"collMod": "user",
"validator": {
"$jsonSchema": {
"bsonType": "object",
"required": ["name"],
"properties": {
"name": {
"bsonType": "string"
}
}
}
}
}
然后在db.py:
with open("user_schema.json", "r") as coll:
data = OrderedDict(json.loads(coll.read())) # Read JSON schema.
name = data["collMod"] # Get name of collection.
db.create_collection(name) # Create collection.
db.command(data) # Add validation to the collection.
有没有办法在不更改db.py 的情况下为user 集合中的name 字段添加唯一索引(仅通过更改user_schema.json)?我知道我可以用这个:
db.user.create_index("name", unique=True)
但是,我在两个地方有关于该集合的信息。我想在user_schema.json 文件中包含集合的所有配置。我需要这样的东西:
{
"collMod": "user",
"validator": {
"$jsonSchema": {
...
}
},
"index": {
"name": {
"unique": true
}
}
}
【问题讨论】:
标签: python database mongodb pymongo unique-index