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);
    }

2 Answers 2

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});
}
Sign up to request clarification or add additional context in comments.

2 Comments

will it ReCreate index every time i insert new docs with CreateOne calling on database?
IndexExistsByName seems to not exist with latest .net Mongo.db Driver 2.9.2. According to stackoverflow.com/questions/35019313/… it's idempotent so not necessary to check for index already existing.
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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.