How to Use InsertBatch With BSon Serialization in a Mongo database in C#

The Insert batch statement is used in a Mongo database for inserting a large amount of JSON data or normal data into a Mongo database. Here I will create an application that will insert a batch of dictionary data into the Mongo database using insert batch.

 
Step 1:
 
Create a console application named "InserBatchforMOngodb".
 
Step 2:
 
Now create a class named "NExtMessage".
  1. public class NextMessage {  
  2.     public List < Dictionary < stringobject >> GetAddress(int MessageId) {  
  3.         var AddressList = new List < Dictionary < string,  
  4.             object >> ();  
  5.   
  6.         for (int i = MessageId; i < MessageId + 9; i++) {  
  7.             Dictionary < stringobject > message = new Dictionary < stringobject > ();  
  8.             message.Add("Id", i);  
  9.             message.Add("DateCreated", DateTime.Today.AddDays(i));  
  10.             message.Add("MessageType""SAS");  
  11.             message.Add("AlertName""Airtel" + i.ToString());  
  12.             AddressList.Add(message);  
  13.         }  
  14.         return AddressList;  
  15.     }  
Here you see I passed the value into the dictionary.
 
Step 3:
 
Now create a class named "DataProvider".
  1. public class DataProvider {  
  2.     /// <summary>  
  3.     ///  
  4.     /// </summary>  
  5.     MongoCollection < BsonDocument > nextMessages, om9Messages;  
  6.     /// <summary>  
  7.     ///  
  8.     /// </summary>  
  9.     MongoServer server;  
  10.     /// <summary>  
  11.     ///  
  12.     /// </summary>  
  13.     MongoDatabase oneConsoleDB;  
  14.   
  15.     /// <summary>  
  16.     /// Opens the connection.  
  17.     /// </summary>  
  18.     private void openConnection() {  
  19.         if (server.State == MongoServerState.Disconnected)  
  20.             server.Connect();  
  21.   
  22.         oneConsoleDB = server.GetDatabase("AirMessage");  
  23.         if (!oneConsoleDB.CollectionExists("NextMessages"))  
  24.             oneConsoleDB.CreateCollection("NextMessages"null);  
  25.   
  26.         nextMessages = oneConsoleDB.GetCollection("NextMessages");  
  27.   
  28.     }  
  29.   
  30.     public DataProvider() {  
  31.         string connectionString = "mongodb://192.168.40.27/?sockettimeout=5m";  
  32.         server = MongoServer.Create(connectionString);  
  33.   
  34.     }  
  35.   
  36.     /// <summary>  
  37.     /// Inserts the batch.  
  38.     /// </summary>  
  39.     public void InsertBatch() {  
  40.         openConnection();  
  41.         nextMessages.RemoveAll();  
  42.         //om9Messages.RemoveAll();  
  43.         var netxMessageBatch = BsonSerializer.Deserialize < BsonDocument[] > (new NextMessage().GetAddress(20).ToJson());  
  44.   
  45.         //var test = netxMessageBatch.Where(t => { t.Elements.Where(k => k.Name.Equals("AlertName") && k.Value == "NetxFM23"); return true; });  
  46.         var test = netxMessageBatch.Where(t => t.Elements.ElementAt(3).Value.Equals("NetxFM23"));  
  47.   
  48.         nextMessages.InsertBatch(netxMessageBatch);  
  49.   
  50.         Console.WriteLine("Inserted successfully");  
  51.         server.Disconnect();  
  52.         Console.ReadLine();  
  53.     }  
  54.     public class NextMessage {  
  55.   
  56.         public List < Dictionary < stringobject >> GetAddress(int MessageId) {  
  57.             var AddressList = new List < Dictionary < string,  
  58.                 object >> ();  
  59.   
  60.             for (int i = MessageId; i < MessageId + 9; i++) {  
  61.                 Dictionary < stringobject > message = new Dictionary < stringobject > ();  
  62.                 message.Add("Id", i);  
  63.                 message.Add("DateCreated", DateTime.Today.AddDays(i));  
  64.                 message.Add("MessageType""SAS");  
  65.                 message.Add("AlertName""Airtel" + i.ToString());  
  66.                 AddressList.Add(message);  
  67.             }  
  68.             return AddressList;  
  69.         }  
  70.     }  
See in the DataProvider method I have written my system IP address. You need to use your own system IP address for connecting the database.
 
Now see this code. This is the most important code before using the insertbatch statement.
  1. var netxMessageBatch = BsonSerializer.Deserialize<BsonDocument[]>(new NextMessage().GetAddress(20).ToJson()); 
Here whenever we are getting dictionary data from the "NextMessage" class we have to deserialize it before putting it into the Mongo database.
 
Now the following code is for saving the dictionary data into the Mongo database.
  1. nextMessages.InsertBatch(netxMessageBatch); 
Step 4:
 
Now in the main program paste the following code:
  1. DataProvider dp = new DataProvider();  
  2. dp.InsertBatch();  
  3. Console.WriteLine(); 
So the complete code is:
  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.Linq;  
  4. using System.Text;  
  5. using MongoDB.Driver;  
  6. using MongoDB.Driver.Builders;  
  7. using MongoDB.Bson;  
  8. using MongoDB.Driver.Internal;  
  9. using MongoDB.Bson.Serialization;  
  10. using MongoDB.Bson.DefaultSerializer;  
  11. using System.IO;  
  12. using mongo = MongoDB;  
  13. using MongoDB.Linq;  
  14.   
  15. namespace INsertBAtchforMOngoDb {  
  16.     public class DataProvider {  
  17.         /// <summary>  
  18.         ///  
  19.         /// </summary>  
  20.         MongoCollection < BsonDocument > nextMessages, om9Messages;  
  21.         /// <summary>  
  22.         ///  
  23.         /// </summary>  
  24.         MongoServer server;  
  25.         /// <summary>  
  26.         ///  
  27.         /// </summary>  
  28.         MongoDatabase oneConsoleDB;  
  29.   
  30.         /// <summary>  
  31.         /// Opens the connection.  
  32.         /// </summary>  
  33.         private void openConnection()  
  34.   
  35.         {  
  36.             if (server.State == MongoServerState.Disconnected)  
  37.                 server.Connect();  
  38.   
  39.             oneConsoleDB = server.GetDatabase("AirMessage");  
  40.   
  41.             if (!oneConsoleDB.CollectionExists("NextMessages"))  
  42.                 oneConsoleDB.CreateCollection("NextMessages"null);  
  43.   
  44.             nextMessages = oneConsoleDB.GetCollection("NextMessages");  
  45.         }  
  46.   
  47.         public DataProvider() {  
  48.             string connectionString = "mongodb://192.168.40.27/?sockettimeout=5m";  
  49.             server = MongoServer.Create(connectionString);  
  50.         }  
  51.   
  52.         /// <summary>  
  53.         /// Inserts the batch.  
  54.         /// </summary>  
  55.         public void InsertBatch() {  
  56.             openConnection();  
  57.             nextMessages.RemoveAll();  
  58.             //om9Messages.RemoveAll();  
  59.             var netxMessageBatch = BsonSerializer.Deserialize < BsonDocument[] > (new NextMessage().GetAddress(20).ToJson());  
  60.   
  61.             //var test = netxMessageBatch.Where(t => { t.Elements.Where(k => k.Name.Equals("AlertName") && k.Value == "NetxFM23"); return true; });  
  62.             var test = netxMessageBatch.Where(t => t.Elements.ElementAt(3).Value.Equals("NetxFM23"));  
  63.             nextMessages.InsertBatch(netxMessageBatch);  
  64.   
  65.             Console.WriteLine("Inserted successfully");  
  66.             server.Disconnect();  
  67.             Console.ReadLine();  
  68.         }  
  69.         public class NextMessage {  
  70.             public List < Dictionary < stringobject >> GetAddress(int MessageId) {  
  71.                 var AddressList = new List < Dictionary < string,  
  72.                     object >> ();  
  73.   
  74.                 for (int i = MessageId; i < MessageId + 9; i++) {  
  75.                     Dictionary < stringobject > message = new Dictionary < stringobject > ();  
  76.                     message.Add("Id", i);  
  77.                     message.Add("DateCreated", DateTime.Today.AddDays(i));  
  78.                     message.Add("MessageType""SAS");  
  79.                     message.Add("AlertName""Airtel" + i.ToString());  
  80.                     AddressList.Add(message);  
  81.                 }  
  82.                 return AddressList;  
  83.             }  
  84.         }  
  85.     }  
  86.     class Program {  
  87.         static void Main(string[] args) {  
  88.             DataProvider dp = new DataProvider();  
  89.             dp.InsertBatch();  
  90.             Console.WriteLine();  
  91.         }  
  92.     }  
When you run the application the results will be as shown in the following figure:
 
Untitled-7.gif
 

Conclusion

 
So in this article, we have seen how to use the insert batch statement with a Mongo database.


Similar Articles