PyMongo create unique index with 2 or more fields

20,447

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
)
Share:
20,447

Related videos on Youtube

Mirza Delic
Author by

Mirza Delic

Software Engineer with strong experience with Python, Django, Flask, MySQL, PostgreSQL, RESTful API services, Vue.js, AngularJS. A lot of experience building scheduling, tracking, POS and ticketing software. More than 6 years of experience developing software and 3 years working remotely. Links: https://www.linkedin.com/in/mirzadelic/ https://github.com/mirzadelic/

Updated on February 16, 2020

Comments

  • Mirza Delic
    Mirza Delic over 4 years

    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.

  • Claudio Santos
    Claudio Santos over 6 years
    here is the link to create_index specification.