# How to add indices to a collection?

  1. Add the index definition to a collection post the property definition. For example:

    collection Lottery{
    	property lotteryName : String
    	...
      property open:Boolean
    	
      index openIndx { // adds an index on open flag
    		up open
    	}
    	
      unique index lotteryNameIndx { //adds an unique index
    		up lotteryName
    	}
      
      index nameOpenIndx { //compound index
    		up lotteryName
    		up open
    	}
    	
    }
    

    Note: Dont forget to save the file

  2. enter sbt shell, run compile command.

  3. run command ensureIndices to apply the indices to the collection on mongo server.

    [Lottery] $ LotteryMongo/collection ensureIndices Lottery
    

Advance options:

  • sparse indices can also be created.
  • index a field with down i.e. reverse ordering
  • index string fields with text option available.

Note: while using compound indices ensure the query conditions honour the index ordering. More details here

REFERENCES