Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MongoDb C# Creating Index and Collection dynamiaclly

Tags:

c#

mongodb

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);
    }
like image 615
Vaibhav shetty Avatar asked Mar 06 '18 11:03

Vaibhav shetty


People also ask

What is MongoDB C driver?

The MongoDB C Driver, also known as “libmongoc”, is a library for using MongoDB from C applications, and for writing MongoDB drivers in higher-level languages. It depends on libbson to generate and parse BSON documents, the native data format of MongoDB.

Can you use MongoDB with C#?

By developing with C# and MongoDB together one opens up a world of possibilities. Console, window, and web applications are all possible. As are cross-platform mobile applications using the Xamarin framework.

Is MongoDB free to use?

MongoDB is a NoSQL database that is open source. MongoDB is available in two editions. One is MongoDB Open Source, which is free as part of the Open-Source Community, but for the other editions, you must pay a License fee. When compared to the free edition, this edition has some advanced features.


1 Answers

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});
}
like image 162
Jehof Avatar answered Oct 25 '22 14:10

Jehof