Search code examples
c#.netmongodbmongodb-.net-driverdatabase

Mongodb failed to insert all my records


I have just started using mongodb as a result of dealing with bulk data's for my new project.I just set up the database and installed c# driver for mongodb and here is what i tried

public IHttpActionResult insertSample()
{

    var client = new MongoClient("mongodb://localhost:27017");
    var database = client.GetDatabase("reznext");
    var collection = database.GetCollection<BsonDocument>("sampledata");
    List<BsonDocument> batch = new List<BsonDocument>();

    for (int i = 0; i < 300000; i++)
    {
       batch.Add(
          new BsonDocument {
          { "field1", 1 },
          { "field2", 2 },
          { "field3", 3 },
          { "field4", 4 }
                 });
    }
    collection.InsertManyAsync(batch);
    return Json("OK");
}

But when i check the collection for documents i see only 42k out of 0.3million records inserted.I use robomongo as client and would like to know what is wrong here.Is there any insertion limit per operation ?


Solution

  • You write async and don't wait for a result. Either wait for it:

    collection.InsertManyAsync(batch).Wait();
    

    Or use synch call:

    collection.InsertMany(batch);