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);
}
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.
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.
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.
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});
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With