Code Snippet - How to Add Index to Document at MongoDB C#
2014/03/011 min read
bookmark this
Table of Contents
Introduction
When working with MongoDB in C#, adding indexes to your document fields improves query performance. Below is a quick code snippet showing how to add an index to both a top-level document field and a subdocument field.
Add Index to a Document Field
// add index to document's field
collection.CreateIndex(IndexKeys.Ascending(_ => _.FieldName));
// add index to subdocument's field
collection.CreateIndex("SubDocument.FieldName");
Conclusion
Adding indexes to your MongoDB collections is essential for query performance. Use IndexKeys.Ascending for typed fields on documents and a string path for subdocument fields.