Introduction
In this article, we will learn how to insert data in MongoDB using Robo 3T. We will learn from basics because I have written this article focusing on beginners. We will also learn how we can set up a MongoDB environment, with an example using a console application. MongoDB is one of the most popular NoSQL databases. Learn more here.
How To Setup MongoDB Environment?
Step 1. Download the MongoDB Installer from this link. Now, run this installer to install MongoDB.
Click on the "Next" button.
Step 2. Now, download Robo 3T and install that from the following link. https://robomongo.org/
Extract and install.
Robo 3T is a cross-platform MongoDB Management UI Tool. You can learn more about it here.
After installation, connect to the local server.
Add the name, while the default address is localhost:27017. Test the connection and click on the "Save" button.
Click on the "Connect" button.
Now, MongoDB is connected to our system. Open Visual Studio and create a new console application. Rename it as InsertOperation.
Now, add MongoDB Driver for C# using NuGet Package Manager.
Step 1. Now, open program.cs and add a connection string, and add the string to the client object.
var Mongodbconnection = "mongodb://localhost";
var Client = new MongoClient(Mongodbconnection);
Step 2. Create a database with the name Employee using Robo 3T.
Step 3. Create a collection (table) with the name EmployeeDetails.
var collection = DB.GetCollection<BsonDocument>("EmployeeDetails ");
Step 4. Now, add some data to the table.
var collection = DB.GetCollection<BsonDocument>("EmployeeDetails");
var Emp = new BsonDocument
{
{"Name","Sanwar"},
{"City","Jaipur"},
{"Age","23"},
{"Department","Software Development"},
{"Technology","Dot Net"}
};
Step 5. Now, add the Emp array into the collection, and use InsertManyAsync function to add the array into the collection.
collection.InsertOneAsync(Emp);
Check the complete code.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using MongoDB.Driver;
using MongoDB.Bson;
namespace InsertOperation
{
class Program
{
static void Main(string[] args)
{
var Mongodbconnection = "mongodb://localhost";
var Client = new MongoClient(Mongodbconnection);
var DB = Client.GetDatabase("Employee");
var collection = DB.GetCollection<BsonDocument>("EmployeeDetails ");
var Emp = new BsonDocument
{
{"Name","Sanwar"},
{"City","Jaipur"},
{"Age","23"},
{"Department","Software Development"},
{"Technology","Dot Net"}
};
collection.InsertOneAsync(Emp);
Console.WriteLine("Press Enter");
Console.ReadLine();
}
}
}
Run the program and check in the database. The data is entered into EmployeeDetails.
Summary
In this article, we learned how we can use Robo 3T tool to insert data in MongoDB database using C# Console Application.