Multiple field Indexing in pymongo

Straight from the doc of createIndex:

>>> my_collection.create_index([("field_name1", TEXT),
...                             ("field_name2", TEXT),
                                unique=True,
                                dropDups=1])

Beware that:

dropDups is not supported by MongoDB 2.7.5 or newer. The option is silently ignored by the server and unique index builds using the option will fail if a duplicate value is detected.

Anyway, this will create a compound index on field_name1 and field_name2.

Finally, please notice there are some limitation when using compound text indexes though.


>>> from pymongo import IndexModel, ASCENDING, DESCENDING
>>> index1 = IndexModel([("hello", DESCENDING),
...                      ("world", ASCENDING)], name="hello_world")

This was mentioned in the doc for pymongo

db[collection_name].create_index([("field_name1" , TEXT),("field_name2", TEXT)],name="index_name"))

This will provide a composite index on [field_name1,field_name2]

http://api.mongodb.org/python/current/api/pymongo/collection.html#pymongo.collection.Collection.create_indexes