Irrespective of what database you use, performance of any query depends on indexing of data fields in the database. MongoDB is no different.
By default MongoDB creates an index on field _id. But it is not very useful because you are not going to be querying data based on this field. Like any RDBMS like Microsoft SQL Server, you will be required to identify fields that you will need to use for indexing. For this discussion, I will use an example from my log aggregation application. I have an object that keeps tracks of user's authentication activity.
public class AuthActivityLog { public string Username { get; set; } public DateTime ActivityOnUtc { get; set; } public int ActivityTypeId{get;set;} public AuthActivityType ActivityType { get => (AuthActivityType)ActivityTypeId; set => ActivityTypeId = (int)value; } public string Location { get; set; } public string Notes { get; set; } public string Device { get; set; } }
When the application processes the data, it queries the records by ActivityOnUtc . If there is no index on this field, then every query will cause all documents to be scanned. That will degrade performance of the application. So, we are going to need put an index on this field.
You can use following steps to add index on a field. I will use example of adding index on ActivityOnUtc from my object.
use ByteMonitor db.AuthActivityLog.createIndex({ActivityOnUtc:-1})
In above example, using -1 indicates that records will be indexed in descending order. A value of 1 indicates ordering of records in descending order.
If you want to verify that index has been added on the field, you can use getIndexes command to list all indexes on a collection. Following snippet shows the indexes on my collection and you can see that it does have an index on ActivityOnUtc field.
db.AuthActivityLog.getIndexes() [ { "v" : 2, "key" : { "_id" : 1 }, "name" : "_id_" }, { "v" : 2, "key" : { "ActivityOnUtc" : -1 }, "name" : "ActivityOnUtc_-1" } ]
In this post, I have talked about adding a simple index on one field only. In subsequent posts, I will discuss more indexing on MongoDB collections and fields.
How to use Lucene In .Net Core project
The database principal owns a database role and cannot be dropped
How to plan CCSP Exam preparation
Develop a MongoDB pipeline to transform data into time buckets
Alert and Confirm pop up using BootBox in AngularJS
AngularJS Grouped Bar Chart and Line Chart using D3
How to lock and unlock account in Asp.Net Identity provider
2023 © Byteblocks, ALL Rights Reserved. Privacy Policy | Terms of Use