How to Connect a Mongo DB Server Through C# .Net Using C# Driver

In this article, I will describe how to connect a Mongo db server in C#.Net and after that how to create the collection in the Mongo db.
 
Before beginning the coding, as we all know we have to open the "mongogod.exe" application.
 
Step 1: First create a console application named "Mongocreateserver".
 
Step 2: After that paste the following code:
  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.Linq;  
  4. using System.Text;  
  5. using MongoDB.Driver;  
  6. using MongoDB.Bson;  
  7. using System.Collections;  
  8. using MongoDB.Bson.Serialization;  
  9. using MongoDB.Driver.Builders;  
  10. using MongoDB;  
  11. namespace mongocreateserver {  
  12.     class Program {  
  13.         static void Main(string[] args) {  
  14.             string connectionString = "mongodb://192.168.40.27";  
  15.             var server = MongoServer.Create(connectionString);  
  16.             if (server.State == MongoServerState.Disconnected)  
  17.                 server.Connect();  
  18.             var OneConsoleDB = server.GetDatabase("One");  
  19.             if (!OneConsoleDB.CollectionExists("NextMessages"))  
  20.                 OneConsoleDB.CreateCollection("NextMessages"null);  
  21.             var NextMessages = OneConsoleDB.GetCollection("NextMessages");  
  22.             server.Disconnect();  
  23.             Console.WriteLine("Server get connected in to this" + connectionString + "Server");  
  24.             server.GetDatabaseNames();  
  25.             server.Disconnect();  
  26.             Console.ReadLine();  
  27.         }  
  28.     }  

See here we are defining the connection string.
 
After that, we are creating the server with the connection string which means specify my system IP.
 
After that, we are creating a server connection.
 
Then we are creating the Database named "One".
 
After that, we are creating the collection name "NextMessages".
 
Finally, we are disconnecting from the server.
 
So when we run the application it will look like:
 
Severconenctinmongodb.jpg
 

Conclusion

 
So in this article, we have seen how to create a connection to the Mongo db and after that create the collection in that Mongo db.


Similar Articles