如何在 pymongo 中创建具有 2 个字段的索引,以便一起唯一?
我有这个代码:
self.db[self.mongo_collection].create_index("url", unique=True)
但我需要对 url
和 category
保持唯一性。
最佳答案
您需要创建一个复合索引并将 unique
设置为 True
,如 documentation 中所述:
If you use the unique constraint on a compound index, then MongoDB will enforce uniqueness on the combination of values rather than the individual value for any or all values of the key.
self.db[self.mongo_collection].create_index(
[("url", pymongo.DESCENDING), ("category", pymongo.ASCENDING)],
unique=True
)
关于python - PyMongo 创建具有 2 个或更多字段的唯一索引,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35812685/