creating indexes in mongodb code example

Example 1: how create an index mongodb

db.collection.createIndex({age:1}) //single field asc index on age field
db.collection.createIndex({firstName:1,lastName:-1})//compound index on firstName asc and lastName desc
db.collection.createIndex({locations:1}) //given locations is an array then a multikey index will be created

Example 2: compound index mongodb

db.collectionName.createIndex({field:value, field:value})


The order of fields listed in a compound index has significance. 
For instance, if a compound index consists of { userid: 1, score: -1 }, 
the index sorts first by userid and then, within each userid value, sorts by score.

Tags:

Misc Example