Difference in creating indexes in mongo db

38 views Asked by At

I would like to know if there is a difference between these two types of index

My goal is to create a composite index in the search for these two keys

   collection.Indexes.CreateOne(
        new CreateIndexModel<Data>(
            Builders<Data>.IndexKeys.Combine(
            Builders<Data>.IndexKeys.Ascending(a => a.Id),
            Builders<Data>.IndexKeys.Ascending(a => a.Name))));
 
  
    collection.Indexes.CreateOne(
        new CreateIndexModel<Data>(
            Builders<Data>
                .IndexKeys
                .Ascending(a => a.Id)
                .Descending(a => a.Name)));

In tests they apparently created the same index, I was unable to identify any difference using Find().Explain()

1

There are 1 answers

4
Salvatore Bernardo On

Here is how the two types of indices you've provided are meant to function:

  1. The first one is an ascending composite index on fields Id and Name. This index would be useful for queries that filter first on Id (in ascending order) and then on Name (also in ascending order).

  2. The second one is a composite index on field Id in ascending order, and Name in descending order. This index would be useful for queries that filter first on Id (in ascending order) and then on Name (in descending order).

Even though these indices might appear similar, they are utilized maximally in different querying circumstances based on the direction (ascending or descending) specified for the fields.

If you try to use Find().Explain() and are not noticing any difference in output, it could be because your test dataset isn't large enough, the fields Id and Name might not have enough unique entries to create a observable difference or your queries aren't tailored in a way to best utilize the order distinctions in these indices.