PyMongo create unique index with 2 or more fields

泄露秘密 提交于 2019-12-04 18:32:18

问题


How can i create index in pymongo with 2 fields, to be unique together?

I have this code:

self.db[self.mongo_collection].create_index("url", unique=True)

but i need to be unique with url and category.


回答1:


You need to create a compound index and set unique to True as mentioned in the 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
)


来源:https://stackoverflow.com/questions/35812685/pymongo-create-unique-index-with-2-or-more-fields

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!