Introduction
This article explains how to get started working with MongoDB using C#. This article will help you learn connecting to a server, creating a database, creating a collection, inserting a document into a collection, removing a document (data) from a collection, querying from a collection and so on. To work with MongoDB you need to download the MongoDB C# driver that supports MongoDB.
Working with MongoDB is the same as working in LINQ and Entity Framework. MongoDB contains the same features and the same work style that LINQ has. This is one of the great features of MongoDB.
Driver Line: https://github.com/mongodb/mongo-csharp-driver/releases
Getting Startded
Before coding, first download the driver, then add the reference of the two DLLs named MogoDB BOSON and MongoDbdriver and use the references of the following namespaces.
- using MongoDB.Bson;
- using MongoDB.Driver;
- using MongoDB.Driver.Builders;
- using MongoDB.Driver.GridFS;
- using MongoDB.Driver.Linq;
Default Connection String: "mongodb://localhost"
The preceding connection string will connect to the local default server having port 27017, you can use a customized connection like "mongodb://192.162.1.xx:27017".
Creating Client
- MongoClient client = new MongoClient(connectionString);
Getting Server Reference
- MongoClient client = new MongoClient(connectionString);
- MongoServer server = client.GetServer();
Getting Database Reference
To create a Mongo database to get a collection (table in SQL Server), where you store your data:
- MongoClient client = new MongoClient(connectionString);
- MongoServer server = client.GetServer();
- MongoDatabase database = server.GetDatabase("Test");
Getting Reference of Collection
Like SQL Server, a MongoDB database contains a collection to store data. To get a reference of the collection, it is required to call the get collection function of the MongoDB database.
- MongoClient client = new MongoClient(connectionString);
- MongoServer server = client.GetServer();
- MongoDatabase database = server.GetDatabase("Test");
- MongoCollection symbolcollection= database.GetCollection<Symbol>("Symbols");
Getting Reference of Collection List
A list of a Mongo collection can also be obtained by calling the GetCollections function of the database, it returns all the collections available in the database in a list.
- MongoClient client = new MongoClient(connectionString);
- MongoServer server = client.GetServer();
- MongoDatabase database = server.GetDatabase("Test");
- List<MongoCollection> collections=database.GetCollections();
- MongoClient client = new MongoClient(connectionString);
- MongoServer server = client.GetServer();
- MongoDatabase database = server.GetDatabase("Test");
- database.DropCollection("Symbols");
Insert into Collection
- MongoClient client = new MongoClient(connectionString);
- MongoServer server = client.GetServer();
- MongoDatabase database = server.GetDatabase("Test");
- MongoCollection symbolcollection= database.GetCollection<Symbol>("Symbols");
- Symbol symbol = new Symbol ();
- symbol.Name = “Star”;
- symbolcollection.Insert(symbol);
- public class Symbol
- {
- public string Name { get; set; }
- public ObjectId ID { get; set; }
- }
Querig list of data
- MongoCollection symbolcollection= database.GetCollection<Symbol>("Symbols")
- List< Symbol > query = symbolcollection.AsQueryable<Symbol>().Where<Entity>(sb => sb.Name == "Star").ToList();
- Symbol symbol = symbolcollection.AsQueryable<Entity>().Where<Entity>(sb => sb.Name == "Kailash").SingleOrDefault();
- MongoCollection symbolcollection= database.GetCollection<Symbol>("Symbols")
- Symbol symbol = symbolcollection.AsQueryable<Entity>().Where<Entity>(sb => sb.Name == "Kailash").SingleOrDefault();
- symbolcollection.Save(symbol);
For example, suppose you want to modify all the columns of an existing table and save the changes; then you need to get the help of the save function.
Updating Data
An alternative to Save is Update. The difference is that Save sends the entire document back to the server, but Update sends just the changes. The Update function takes a parameter.
For example: suppose you need to change some columns of a table and send only the updated column value to the server, in that case you need to use the Update function of the MongoDB collection.
- MongoCollection symbolcollection= database.GetCollection<Symbol>("Symbols")
- var query3 = Query<Symbol>.EQ(e => e.Id, ("0000000000021325640.0");
- var update = Update<Symbol>.Set(e => e.Name, "abc"); // update modifiers
- symbolcollection.Update(query3, update);
To remove an existing documet from the collection the Remove fuction helps. The Remove function takes an object of an entity as a parameter.
- MongoCollection symbolcollection= database.GetCollection<Symbol>("Symbols")
- var query2 = Query< Symbol >.EQ(fd=>fd.Id, new ObjectId("0000000000021325640.0"));
- symbolcollection.Remove(query2);
- symbolcollection.RemoveAll();
- using System;
- using System.Collections.Generic;
- using System.Linq;
- using System.Text;
- using System.Timers;
- using MongoDB.Bson;
- using MongoDB.Driver;
- using MongoDB.Driver.Builders;
- using MongoDB.Driver.GridFS;
- using MongoDB.Driver.Linq;
- using System.Data.SqlClient;
- namespace MongodbRND
- {
- class Program
- {
- static void Main(string[] args)
- {
- Console.WriteLine("Mongo DB Test Application");
- Console.WriteLine("====================================================");
- Console.WriteLine("Started By:Kailash Chandra Behera");
- Console.WriteLine("Started On: 14 July 2014");
- Console.WriteLine("Configuration Setting: 172.16.1.24:27017");
- Console.WriteLine("====================================================");
- Console.WriteLine("Initializaing connection");
- string connectionString = "mongodb://172.16.1.24:27017";
- Console.WriteLine("Creating Client..........");
- MongoClient client = null;
- try
- {
- client = new MongoClient(connectionString);
- Console.WriteLine("Client Created Successfuly........");
- Console.WriteLine("Client: " + client.ToString());
- }
- catch (Exception ex)
- {
- Console.WriteLine("Filed to Create Client.......");
- Console.WriteLine(ex.Message);
- }
- Console.WriteLine("Initianting Mongo Db Server.......");
- MongoServer server = null;
- try
- {
- Console.WriteLine("Getting Servicer object......");
- server = client.GetServer();
- Console.WriteLine("Server object created Successfully....");
- Console.WriteLine("Server :" + server.ToString());
- }
- catch (Exception ex)
- {
- Console.WriteLine("Filed to getting Server Details");
- Console.WriteLine(ex.Message);
- }
- Console.WriteLine("Initianting Mongo Databaser.........");
- MongoDatabase database = null;
- try
- {
- Console.WriteLine("Getting reference of database.......");
- database = server.GetDatabase("Kailash");
- Console.WriteLine("Database Name : " + database.Name);
- }
- catch (Exception ex)
- {
- Console.WriteLine("Failed to Get reference of Database");
- Console.WriteLine("Error :" + ex.Message);
- }
- try
- {
- Console.WriteLine("Deleteing Collection Symbol");
- database.DropCollection("Symbol");
- }
- catch (Exception ex)
- {
- Console.WriteLine("Failed to delete collection from Database");
- Console.WriteLine("Error :" + ex.Message);
- }
- Console.WriteLine("Getting Collections from database Database.......");
- MongoCollection symbolcollection = null;
- try
- {
- symbolcollection = database.GetCollection<Symbol>("Symbols");
- Console.WriteLine(symbolcollection.Count().ToString());
- }
- catch (Exception ex)
- {
- Console.WriteLine("Failed to Get collection from Database");
- Console.WriteLine("Error :" + ex.Message);
- }
- ObjectId id = new ObjectId();
- Console.WriteLine("Inserting document to collection............");
- try
- {
- Symbol symbol = new Symbol ();
- symbol.Name = “Star”;
- symbolcollection.Insert(symbol);
- id = symbol.ID;
- Symbol symbol = new Symbol ();
- symbol.Name = “Star1”;
- symbolcollection.Insert(symbol);
- id = symbol.ID;
- Console.WriteLine(symbolcollection.Count().ToString());
- }
- catch (Exception ex)
- {
- Console.WriteLine("Failed to insert into collection of Database " + database.Name);
- Console.WriteLine("Error :" + ex.Message);
- }
- try
- {
- Console.WriteLine("Preparing Query Document............");
- List< Symbol > query = symbolcollection.AsQueryable<Entity>().Where<Entity>(sb => sb.Name == "Kailash").ToList();
- Symbol symbol = symbolcollection.AsQueryable<Entity>().Where<Entity>(sb => sb. ID == id).ToList();
- }
- catch (Exception ex)
- {
- Console.WriteLine("Failed to query from collection");
- Console.WriteLine("Exception :" + ex.Message);
- }
- Console.WriteLine("");
- Console.WriteLine("====================================================");
- Console.ReadLine();
- }
- }
- public class Symbol
- {
- public string Name { get; set; }
- public ObjectId ID { get; set; }
- }
- }
In this illustration we learned about MongoDB and how to work with MongoDB using C#. We learned connecting to a server, getting the database reference, creating a collection, inserting into a collection, querying from a collection and so on.
imu imuPosted Sep 28, 2018, 3:16 PM
Hi does mongo support transaction.... if i want to insert in two table one of the table did not insert (commit) the transaction will roll back???
MOHAN BEHARAPosted Mar 23, 2018, 4:03 AM
Please share best pdfs on mongoDB (step by step process) to [email protected]
AKSHAY RPosted Jan 19, 2018, 9:21 AM
Nice comments pleas keep the good work up
Hemant BharadwajPosted Sep 26, 2017, 11:50 AM
Kailash Chandra Behera in the line 122 "List< Symbol > query = symbolcollection.AsQueryable<Entity>().Where<Entity>(sb => sb.Name == "Kailash").ToList(); " where is the definition of Entity coming from ? I am facing reference errors.
Hemant BharadwajPosted Sep 26, 2017, 11:49 AM
In the line 122 "List< Symbol > query = symbolcollection.AsQueryable<Entity>().Where<Entity>(sb => sb.Name == "Kailash").ToList(); " where is the definition of Entity coming from ? I am facing reference errors.
Hamid KhanPosted Sep 26, 2017, 9:57 AM
VERY NICE......................
GouseSakhalean MohammadPosted Aug 8, 2017, 6:12 AM
The code is not working
Abdul Amin KhanPosted Mar 31, 2017, 6:04 AM
What if Entity in this Code
Former memberPosted Aug 29, 2015, 7:32 AM
thanks
Shakti SaxenaPosted Aug 28, 2015, 9:07 AM
Nice Share.. Thanks :)
Debendra DashPosted Jul 10, 2015, 6:53 AM
good one sir.........