Once you have settled on an algorithm for choosing a unique key, is there a way to guarantee uniqueness? One very useful and effective solution is to create a unique index on the key field. This has two benefits:
- MongoDB prevents your application from adding a document with a duplicate key.
- Searches involving this key becomes faster and more efficient.
The general rule for creating indexes in MongoDB is to create indexes on fields frequently used in queries. Do not go overboard on creating indexes, however, as they introduce extra overhead to maintain them.Â
Using the mongo shell, you can create an index on a field as follows:
db.<name_of_collection>.createIndex(keys, options);
Let's jump right into an example involving the users collection and the userKey field mentioned earlier in this subsection. Here is the query that creates a unique index on the userKey field in ascending order:
db.users.createIndex( { "userKey" : 1 }, { "unique...