Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PyMongo create unique index with 2 or more fields

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.

like image 795
Mirza Delic Avatar asked Mar 05 '16 09:03

Mirza Delic


1 Answers

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
)
like image 69
styvane Avatar answered Nov 03 '22 05:11

styvane