Skip to main content

Insert Multiple Records into Mongodb Using C# and .Net

    To insert multiple records ( documents ) into MongoDB collection, we need to use InsertManyAsync to insert the array of documents in single shot.

Here I am connecting with the ‘test’ database and ‘store’ collection inserting two documents in single execution. Make Sure that you have used appropriate references in namespace section, also check your database is accessible.

C# Code

using System;
using System.Collections.Generic;
using MongoDB.Bson;
using MongoDB.Driver;

namespace InsMulDtls
    class Program
        static void Main(string[] args)
            var Client = new MongoClient();
            var DB = Client.GetDatabase("test");
            var collection = DB.GetCollection<BOStore>("store");
            var document = new BOStore
                ProductName = "JBL T150A",
                Price = "11.5",
                MadeIn = "japan"
            var document2 = new BOStore
                ProductName = "WH-208",
                Price = "9.20",
                MadeIn = "China"

          collection.InsertManyAsync(new [] { document, document2 });

          Console.WriteLine("Press Enter");
    class BOStore
        public ObjectId ID { get; set; }
        public string ProductName { get; set; }
        public string Price { get; set; }
        public string MadeIn { get; set; }


  1. It's helpful for me
    thanks for the code

  2. How can new documents be created or edited Dynamically? Would we be required to create a new object for each new Document? Can I use classes for this?

  3. It is possible to insert records from sql database , if it is possible please help on this.


Post a Comment