Creating indexes in NoSQL / Document-based databases is quite different compared to traditional relational databases. Since the former are schema-less (there is no table creation), indexes do not get created when the collection or the document is created or inserted. Here is a quick tip that will create all the indexes defined in your documents when using Symfony 2 and Doctrine ODM for MongoDB.

Indexes are a great way to speed up your queries, in fact, it is a crime not to include them in your documents. To create an index for a field in your document, simply declare it in the annotation:

/** @Document */
class User
{
    /** @Id */
    public $id;

    /** @String @Index */
    public $username;
}

You can find more information about indexes in the Doctrine ODM documentation site.

There is no console command in Symfony2 to create the indexes, but the Doctrine ODM API provides a way to create these. You can add the following code to an action in a controller or create a console command and include this code:

$dm = $this->container->get('doctrine.odm.mongodb.document_manager');
$dm->getSchemaManager()->ensureIndexes();

This will not only speed up find queries, it will prevent MongoDB from issuing an error when trying to sort documents with fields that have no indexes on, which may work if you have a few documents, but may suddenly start happening after you inserted several hundred of them.