Setting Indexes in MongoDB collections¶
Not every project is using the same indexes. As it turned out, the developers could not agree on a common set of indexes. The main reason were custom indexes (not managed by doctrine) which were deleted when using doctrine. Therefore, we decided to provide a list of indexes that can be set in the MongoDB collections. The indexes are not mandatory, but they can improve the performance of the application.
Indexes¶
There are several ways to set indexes in MongoDB collections. The following list contains the most common ways to set up a custom index.
Using Doctrine MongoDB ODM¶
Doctrine MongoDB ODM provides a way to set up indexes in the MongoDB collections. The indexes can be set using the
@MongoDB\Index attribute. The following example shows how to set up an index in a MongoDB collection by adding the
attribute to a property in the document class:
#[MongoDB\Field(type: Type::DATE, nullable: true)]
#[MongoDB\Index(keys: ["datetime" => "asc"])]
private ?DateTime $datetime;
The next (and final step) is to update the MongoDB collection. This can be done by running the following command:
The first command used the default document manager which is responsible for the synQup default database. The second command used the document managerlogs. It is responsible for the logs database.
Additionally, you can add the --disable-validators option to the command to disable the validation of the
indexes. This can be useful in some scenarios.
Using the MongoDB shell¶
You can also create indexes directly in the MongoDB shell. The following example shows how to create an index in the
logEntry collection:
Warning
Be aware that building an index can take some time. If you have a large collection, it can take a while to build the index.
Using an index for creating capped collections¶
We created a custom CLI command to create capped collections.
bin/console synqup:convert-capped-collection
bin/console synqup:convert-capped-collection --collection=logEntry --size=10737418240 --drop-and-recreate
The first command creates a capped collection with the default collection (i.e. logEntry) and the default size
of 5368709120 bytes. The second command will set a custom size of 10737418240 bytes (10GB).
If the option --drop-and-recreate is set, the collection is dropped and recreated.