Add Mongo Index Via Javascript

99 Views Asked by At

I want to add an index to my mongo collection outside of the interactive Mongo shell.

We're building in Python, so I could set it through MongoEngine, however, I'd greatly prefer to set the indexes directly.

Can I use db.eval() to make this happen?

2

There are 2 best solutions below

1
lobster1234 On BEST ANSWER

You can use collection_name.create_index API from Python.

http://api.mongodb.org/python/1.11/api/pymongo/collection.html

If using Javascript, the problem with eval() is that it needs a write lock, and creating an index itself needs a write lock. I do not think you can use eval() for anything that needs a write lock due to this reason.

0
Phillip Kovalev On

You can use QuerySet.ensure_index.