Hello everyone. My last article demonstrated how to interact with MongoDB database server from a simple C# console application. Now, when you build enterprise applications using MongoDB, your local database server should always be up and running for 365 days or more. This is not appropriate for enterprise applications. Also mainatining your local server in the running state for such a long time is quite a difficult task. So what is the solution for this problem? Simple, you put your database server in the cloud - Azure cloud. More specifically Azure Cosmos DB. This article will revolve around on how to create MongoDB database server in Azure cloud and then connect it with your application.
Before getting started, let us know what is Azure Cosmos DB in brief.
According to the Azure Cosmos DB documentation by Microsoft :
"Azure Cosmos DB is Microsoft's globally distributed, multi-model database. With the click of a button, Azure Cosmos DB enables you to elastically and independently scale throughput and storage across any number of Azure's geographic regions. It offers throughput, latency, availability, and consistency guarantees with comprehensive service level agreements (SLAs), something no other database service can offer. Azure Cosmos DB contains a write optimized, resource governed, schema-agnostic database engine that natively supports multiple data models: key-value, documents, graphs, and columnar. It also supports many APIs for accessing data including MongoDB, DocumentDB SQL, Gremlin (preview), and Azure Tables (preview), in an extensible manner."
For more information, you can refer to this
link.
To get started, you need to have Azure subscription. If you don't, then you can try out 30 days trial version or you can check out the
Visual Studio Dev Essentials program.
Let's see how to work with MongoDB in Azure Cosmos DB.
1. Login to
Azure portal.
2. Go to New
3. Type MongoDB in the search bar.
4. Select Database as a service for MongoDB
5. Click Create button
6. Fill up the details and click Create
7. Once your resource group and when the resources are successfully deployed, click on it to view.
8. Initially your Azure Cosmos DB account will not have any database or collection. To create one, click on Add Collection.
9. Fill up the details and click OK. Once you do that,your collection will be shown.
10. Click on the Data Explorer and execute Mongo queries just like the local Mongo server.
11. Now click Connection String and copy the connection string.
12. Now paste in our last C# console program. Specify the database name and the collection name.
Here is the C# source code,
- using System;
- using System.Collections.Generic;
- using System.Linq;
- using System.Text;
- using System.Threading.Tasks;
- using MongoDB.Driver;
- using MongoDB.Bson;
-
- namespace ConsAppMongoDBCRUD
- {
- class Program
- {
- static void Main(string[] args)
- {
- try
- {
- MongoClient dbClient = new MongoClient("<your connection string>");
-
-
- var dbList = dbClient.ListDatabases().ToList();
-
- Console.WriteLine("The list of databases are :");
- foreach (var item in dbList)
- {
- Console.WriteLine(item);
- }
-
- Console.WriteLine("\n\n");
-
-
- IMongoDatabase db = dbClient.GetDatabase("MyWorkMongoDB");
- var collList = db.ListCollections().ToList();
- Console.WriteLine("The list of collections are :");
- foreach (var item in collList)
- {
- Console.WriteLine(item);
- }
-
- var personColl = db.GetCollection<BsonDocument>("PersonsCollection");
-
-
- BsonElement personFirstNameElement = new BsonElement("PersonFirstName", "Sankhojjal");
-
- BsonDocument personDoc = new BsonDocument();
- personDoc.Add(personFirstNameElement);
- personDoc.Add(new BsonElement("PersonAge", 23));
-
- personColl.InsertOne(personDoc);
-
-
- BsonElement updatePersonFirstNameElement = new BsonElement("PersonFirstName", "Souvik");
-
- BsonDocument updatePersonDoc = new BsonDocument();
- updatePersonDoc.Add(updatePersonFirstNameElement);
- updatePersonDoc.Add(new BsonElement("PersonAge", 24));
-
- BsonDocument findPersonDoc = new BsonDocument(new BsonElement("PersonFirstName", "Sankhojjal"));
-
- var updateDoc = personColl.FindOneAndReplace(findPersonDoc, updatePersonDoc);
-
- Console.WriteLine(updateDoc);
-
-
- BsonDocument findAnotherPersonDoc = new BsonDocument(new BsonElement("PersonFirstName", "Sourav"));
-
- personColl.FindOneAndDelete(findAnotherPersonDoc);
-
-
- var resultDoc = personColl.Find(new BsonDocument()).ToList();
- foreach (var item in resultDoc)
- {
- Console.WriteLine(item.ToString());
- }
- }
- catch (Exception ex)
- {
- Console.WriteLine(ex.Message);
- }
-
- Console.ReadKey();
- }
- }
- }
That's all. I hope you find it useful. Until then stay tuned and keep coding!!!