Getting Started With MongoDB - MongoDB In Azure Cosmos DB

Introduction 

 
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 maintaining your local server in the running state for such a long time is quite a difficult task. So what is the solution to this problem? Simple, you put your database server in the cloud - Azure cloud. More specifically Azure Cosmos DB. This article will revolve around how to create a 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 an 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. Log in to the 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,
  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.Linq;  
  4. using System.Text;  
  5. using System.Threading.Tasks;  
  6. using MongoDB.Driver;  
  7. using MongoDB.Bson;  
  8.   
  9. namespace ConsAppMongoDBCRUD  
  10. {  
  11.     class Program  
  12.     {  
  13.         static void Main(string[] args)  
  14.         {  
  15.             try  
  16.             {  
  17.                 MongoClient dbClient = new MongoClient("<your connection string>");  
  18.   
  19.                 //Database List  
  20.                 var dbList = dbClient.ListDatabases().ToList();  
  21.   
  22.                 Console.WriteLine("The list of databases are :");  
  23.                 foreach (var item in dbList)  
  24.                 {  
  25.                     Console.WriteLine(item);  
  26.                 }  
  27.   
  28.                 Console.WriteLine("\n\n");  
  29.   
  30.                 //Get Database and Collection  
  31.                 IMongoDatabase db = dbClient.GetDatabase("MyWorkMongoDB");  
  32.                 var collList = db.ListCollections().ToList();  
  33.                 Console.WriteLine("The list of collections are :");  
  34.                 foreach (var item in collList)  
  35.                 {  
  36.                     Console.WriteLine(item);  
  37.                 }  
  38.   
  39.                 var personColl = db.GetCollection<BsonDocument>("PersonsCollection");  
  40.   
  41.                 //CREATE  
  42.                 BsonElement personFirstNameElement = new BsonElement("PersonFirstName""Sankhojjal");  
  43.   
  44.                 BsonDocument personDoc = new BsonDocument();  
  45.                 personDoc.Add(personFirstNameElement);  
  46.                 personDoc.Add(new BsonElement("PersonAge", 23));  
  47.   
  48.                 personColl.InsertOne(personDoc);  
  49.   
  50.                 //UPDATE  
  51.                 BsonElement updatePersonFirstNameElement = new BsonElement("PersonFirstName""Souvik");  
  52.   
  53.                 BsonDocument updatePersonDoc = new BsonDocument();  
  54.                 updatePersonDoc.Add(updatePersonFirstNameElement);  
  55.                 updatePersonDoc.Add(new BsonElement("PersonAge", 24));  
  56.   
  57.                 BsonDocument findPersonDoc = new BsonDocument(new BsonElement("PersonFirstName""Sankhojjal"));  
  58.   
  59.                 var updateDoc = personColl.FindOneAndReplace(findPersonDoc, updatePersonDoc);  
  60.   
  61.                 Console.WriteLine(updateDoc);  
  62.   
  63.                 //DELETE  
  64.                 BsonDocument findAnotherPersonDoc = new BsonDocument(new BsonElement("PersonFirstName""Sourav"));  
  65.   
  66.                 personColl.FindOneAndDelete(findAnotherPersonDoc);  
  67.   
  68.                 //READ  
  69.                 var resultDoc = personColl.Find(new BsonDocument()).ToList();  
  70.                 foreach (var item in resultDoc)  
  71.                 {  
  72.                     Console.WriteLine(item.ToString());  
  73.                 }  
  74.             }  
  75.             catch (Exception ex)  
  76.             {  
  77.                 Console.WriteLine(ex.Message);  
  78.             }  
  79.   
  80.             Console.ReadKey();  
  81.         }  
  82.     }  
  83. }   
That's all. I hope you find it useful. Until then stay tuned and keep coding!!!


Similar Articles