The InsertOneAsync method and the InsertManyAsync method are used to add documents to a collection in MongoDB. If documents to a collection that does not exist, MongoDB will create the collection.
We can use InsertManyAsync while inserting more than one document.
Follow the Install and Connect to MongoDB step to connect to a running MongoDB instance.
Below code will Insert a document into a collection named users. The operation will create the collection if the collection does not currently exist.
using System;
using System.Threading.Tasks;
using MongoDB.Bson;
using MongoDB.Driver;
namespace MongoDB
{
class Program
{
static void Main(string[] args)
{
InsertDoc(args).Wait();
Console.WriteLine("Press Enter");
Console.ReadLine();
}
static async Task InsertDoc(string[] args)
{
var _connectionString = "mongodb://localhost:27017";
var _client = new MongoClient(_connectionString);
var _database = _client.GetDatabase("blog");
var _collection = _database.GetCollection("users");
var _document = new BsonDocument
{
{ "Name", "test user" },
{ "Email", "test@xxx.com" },
{ "Address1", "5619 other st" },
{ "City", "other city" },
{ "ZipCode", "12345" },
{ "Country", "test country" }
};
await _collection.InsertOneAsync(_document);
}
}
}