می توان بر روی کلیدی که خیلی استفاده می شود ایندکس ساخت
db.collection.ensureIndex( { a: 1 } )
برای افزایش سرعت کوئری در مونگو دی بی می توان روی کلیدی که به صورت
unique است ایندکس ساخت
db.people.ensureIndex( { "phone-number": 1 }, { unique: true } )
db.people.ensureIndex( { "phone-number": 1 }, { unique: true, sparse: true } )
In many situations you will want to combine the unique constraint with the sparse option. When MongoDB indexes a field, if a document does not have a value for a field, the index entry for that item will be null. Since unique indexes cannot have duplicate values for a field, without the sparse option, MongoDB will reject the second document and all subsequent documents without the indexed field. Consider the following prototype.
You can also enforce a unique constraint on compound indexes, as in the following prototype:
db.collection.ensureIndex( { a: 1, b: 1 }, { unique: true } )
برای حذف داده های تکراری هنگام ایجاد ایندکس یونیک
db.collection.ensureIndex( { a: 1 }, { unique: true, dropDups: true } )
Warning
Specifying { dropDups: true } may delete data from your database. Use with extreme caution
پایتون
db.stem.create_index( "stem",pymongo.ASCENDING )
db.stem.ensure_index( "stem",unique=True )