Harpreet Singh
Harpreet Singh

Reputation: 49

How to check index in MongoDB C# (existing or not) as IndexExist is deprecated from newer version

I just updated the old MongoDB C# drivers to 2.7.3 version and after updating it from nuget packages i got lot of errors line

EnsureIndex is not defined

and

IndexExists not defined

ping is not defined

and

getServer is not defined

so is their and update document or documentation which will explain how to get these with a newer version.

var connectionString = string.Format("mongodb://{0}:{1}", mongoServerInstance.Address.Host, mongoServerInstance.Address.Port);
            connectionString = ReplaceHostNames(connectionString);
            _logger.Debug("checking for indexes on server, {0}", mongoServerInstance.Address.Host);
            var settings = MongoClientSettings.FromUrl(new MongoUrl(connectionString));
            settings.ConnectionMode = ConnectionMode.Direct;
            settings.ReadPreference = ReadPreference.SecondaryPreferred;
            var mongoClient = new MongoClient(settings);
            var listMongo = mongoClient.ListDatabases();
            var server = mongoClient.GetServer();

            foreach (var index in MongoRepositoryConfiguration.Indexes)
            {
                var mongoDataBase = mongoClient.GetDatabase(index.DatabaseName);

                if (!mongoClient.GetDatabase(index.DatabaseName)
                            .GetCollection<BsonDocument>(index.CollectionName)
                            .IndexExists(index.MongoIndexKeys))
                {
                    if (index.IndexName != "")
                    {
                        if (!mongoClient.GetDatabase(index.DatabaseName)
                                   .GetCollection<BsonDocument>(index.CollectionName)
                                   .IndexExistsByName(index.IndexName))
                        {
                            AddIndexToList(index, nonExistentIndexes);
                        }
                    }
                    else
                    {
                        AddIndexToList(index, nonExistentIndexes);
                    }
                }
            }

            server.Disconnect();

Upvotes: 3

Views: 6143

Answers (3)

Matthias M&#252;ller
Matthias M&#252;ller

Reputation: 572

For using in C# with the nuget package MongoDB.Driver V 2.14.1 I created an extension method for IMongoCollection to check, wether an index for a given name already exists in that collection:

public static bool HasIndex<T>(this IMongoCollection<T> mongoCollection, string indexName)
{
    var indexes = mongoCollection.Indexes.List().ToList();
    var indexNames = indexes
        .SelectMany(i => i.Elements)
        .Where(e => string.Equals(e.Name, "name", StringComparison.CurrentCultureIgnoreCase))
        .Select(n => n.Value.ToString()).ToList();

    return indexNames.Contains(indexName);
}

So whenever you want to check if an index exists in a specific collection of a mongo database you can check it via this example:

var database = _mongoClient.GetDatabase("Database");
var examples = database.GetCollection<Example>("Examples");

var hasIndex = examples.HasIndex("ExampleIndex");

Upvotes: 1

GPuri
GPuri

Reputation: 833

You can check for index already exists and then create one

var db = _mongoClient.GetDatabase("db");
var coll = db.GetCollection<Coll>("collName");
var indexes = (await (await coll.Indexes.ListAsync()).ToListAsync()).Select(_ => _.GetElement("name").Value.ToString()).ToList();
// If index not present create it else skip.
if (indexes.Where(_ => _.Equals("<Index Name>")).Count() == 0)
{
    // Create Index here
}

Upvotes: 1

Dĵ ΝιΓΞΗΛψΚ
Dĵ ΝιΓΞΗΛψΚ

Reputation: 5679

in 2.x driver you can get details of indexes for a given collection via the collection.Indexes.List() method. here's an example of creating two indexes and getting their names using MongoDB.Entities [disclaimer: i'm the author]

using MongoDB.Entities;
using MongoDB.Driver;
using System;

namespace StackOverflow
{
    public class Program
    {
        public class User : Entity
        {
            public string FirstName { get; set; }
            public string LastName { get; set; }
            public int Age { get; set; }
        }

        static void Main(string[] args)
        {
            new DB("test");

            DB.Index<User>()
              .Key(u => u.FirstName, KeyType.Text)
              .Key(u => u.LastName, KeyType.Text)
              .Create();

            DB.Index<User>()
              .Key(u => u.Age, KeyType.Ascending)
              .Create();

            var indexes = DB.Collection<User>().Indexes.List().ToList();

            foreach (var index in indexes)
            {
                Console.WriteLine(index.GetElement("name"));
            }

            Console.Read();
        }
    }
}

Upvotes: 3

Related Questions