Home > Mobile >  How to insert documents in batches (Size of 10) in mongodb using c#
How to insert documents in batches (Size of 10) in mongodb using c#

Time:07-28

Below code snippet generates a BsonDocument List of 3000 records.

List<BsonDocument> batch = new List<BsonDocument>();
for (int i = 0; i < 3000; i  )
{
   batch.Add(
       new BsonDocument {
           { "field1", 1 },
           { "field2", 2 },
           { "field3", 3 },
           { "field4", 4 }
        });
}

Below code inserts all records one shot. I need to insert these 3000 records in Mongodb in batches(each batch with 10 records) using InsertMany operation. Appreciate if any one can help on this.

var mongo = new MongoClient("mongodb://10.44.4.59");
MongoServer server = mongo.GetServer();

MongoDatabase test = server.GetDatabase("server_info");
var category = test.GetCollection("test_collection");

CodePudding user response:

You can split your list of 3k into chunks like so:

var batches = batch.Chunk(10);
  • Related