PyMongo create unique index with 2 or more fields

前端 未结 1 793
感动是毒
感动是毒 2021-01-01 17:00

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         


        
相关标签:
1条回答
  • 2021-01-01 17:51

    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
    )
    
    0 讨论(0)
提交回复
热议问题