28

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.

styvane
  • 59,869
  • 19
  • 150
  • 156
Mirza Delic
  • 4,119
  • 12
  • 55
  • 86

1 Answers1

47

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
)
styvane
  • 59,869
  • 19
  • 150
  • 156
  • 1
    here is the link to [create_index](https://api.mongodb.com/python/current/api/pymongo/collection.html#pymongo.collection.Collection.create_index) specification. – Claudio Santos Feb 03 '18 at 13:34
  • The link to create_index has moved: https://pymongo.readthedocs.io/en/stable/api/pymongo/collection.html#pymongo.collection.Collection.create_index – darkless Mar 01 '23 at 09:36