Hi,
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.
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");
Console.ReadLine();
}
}
class BOStore
{
public ObjectId ID { get; set; }
public string ProductName { get; set; }
public string Price { get; set; }
public string MadeIn { get; set; }
}
}
3 Comments
It's helpful for me
ReplyDeletethanks for the code
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?
ReplyDeleteIt is possible to insert records from sql database , if it is possible please help on this.
ReplyDelete