PyMongo creates a unique index with two or more fields

How can I create an index in pymongo with two 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 .

+6
source share
1 answer

You need to create a composite index and set unique to True , as stated in the documentation :

If you use a unique constraint for a composite index, MongoDB will apply uniqueness in a combination of values, rather than a single value for any or all of the key values.

 self.db[self.mongo_collection].create_index( [("url", pymongo.DESCENDING), ("category", pymongo.ASCENDING)], unique=True ) 
+9
source

All Articles