7

I am creating a collection dynamically using C#(MongDB driver). I found that collection gets created only if atleast one document is inserted into it. i am doing as below. Since i am calling CreatOne for every insert to create index, will it ReCreate index every time i insert new docs? Is there any better way for creating collection and index dynamically than this?

public static void CreatAndInsert(double value1, double value2, string collectoinName)
    {
        var connectionString = "mongodb://localhost";
        var client = new MongoClient(connectionString);
        var database = client.GetDatabase("sample");

        //Create Index
        var indexDefn = Builders<BsonDocument>.IndexKeys.Ascending("datetime");
        string collectionName = collectoinName;
        database.GetCollection<BsonDocument>(collectionName).Indexes.CreateOne(indexDefn, new CreateIndexOptions() { Background = true, Sparse = true});

        //Create Collection
        var dbcollection = database.GetCollection<BsonDocument>(collectionName);

        var document = new BsonDocument
                {
                    { "_id", ObjectId.GenerateNewId()},
                    { "Key1", value1 },
                    { "Key2", value2},
                    { "datetime", DateTime.Now }
                };

        dbcollection.InsertOne(document);
    }
Vaibhav shetty
  • 372
  • 1
  • 4
  • 15

2 Answers2

3

You could check first if the index exists, before creating it. The API provides a method IndexExistsByName to check if an index exists or not.

var collection = database.GetCollection<BsonDocument>(collectionName);

if (! collection.IndexExistsByName("myindex")) {
  collection.Indexes.CreateOne(indexDefn, new CreateIndexOptions() { Background = true, Sparse = true});
}
Jehof
  • 34,674
  • 10
  • 123
  • 155
  • 1
    will it ReCreate index every time i insert new docs with CreateOne calling on database? – Vaibhav shetty Mar 06 '18 at 12:00
  • 4
    IndexExistsByName seems to not exist with latest .net Mongo.db Driver 2.9.2. According to https://stackoverflow.com/questions/35019313/checking-if-an-index-exists-in-mongodb it's idempotent so not necessary to check for index already existing. – Markus Oct 08 '19 at 14:40
0

At the Moment of November 2021, Your Code works perfectly fine even when you don't insert a value. I'm using MongoDB.Driver at Version 2.13.2.

public static void CreateCollection(string collectoinName)
    {
        var connectionString = "mongodb://SERVER_ADDRESS:PORT";
        var client = new MongoClient(connectionString);
        var database = client.GetDatabase("test");

        //Create Index
        var indexDefn = Builders<BsonDocument>.IndexKeys.Ascending("datetime");
        string collectionName = collectoinName;
        database.GetCollection<BsonDocument>(collectionName).Indexes.CreateOne(indexDefn, new CreateIndexOptions() { Background = true, Sparse = true });

        
    }

enter image description here

shehryar
  • 98
  • 1
  • 8