pymongo 集合模式通过验证器模式在字段上定义唯一索引

pymongo collection schema define unique index on field thorugh validator schema

我想知道是否有任何方法可以通过验证程序模式定义唯一字段?

这是我的示例代码,我想删除行:

db.testcollection.create_index('author', unique=True)

有什么方法可以在验证器模式中定义它吗?

from pymongo import MongoClient, errors
from bson import ObjectId
import datetime


client = MongoClient()
db = client.testdb
coll_name = 'testcollection'

# check if collection exist and drop it
collist = db.list_collection_names()
if coll_name in collist:
    col = db[coll_name]
    col.drop()
    print('Collection ' + coll_name + ' dropped.')

# create test collection with validator schema
collection = db.create_collection(coll_name, validator={
        '$jsonSchema': {
            'bsonType': 'object',
            'additionalProperties': True,
            'required': ['author', 'content'],
            'properties': {
                'author': {
                    'bsonType': 'string',
                },
                'content': {
                    'bsonType': 'string',
                    'description': 'Default text.'
                }
            }
        }
    })

# create index unique index on author field
db.testcollection.create_index('author', unique=True)

# define post data for testing
post = {'author': 'Dule Pacov',
        'content': 'Best article about PyMongo.',
        'tags': ['mongo', 'python', 'pymongo'],
        'date': datetime.datetime.utcnow()}

# testing if duplicate key error works
i = 0
while i < 3:
    i = i + 1
    try:
        # try insert data into collection
        post_id = collection.insert_one(post).inserted_id

    except errors.DuplicateKeyError:
        # print error if duplicate author key was found
        print('Duplicate key found.')

    except Exception as e:
        # print other error reasons
        print(str(e))

# print data for specific ObjectId
print(collection.find_one({"_id": ObjectId(post_id)}))

架构验证和唯一索引是两个独立的操作。

使用 create_index 命令有什么问题?