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;
Connection String SyntaxDefault 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);
Like a SQL connection you are required you create a MongoDB client, the code above creates an object of Mongoclient that takes a connection string as a parameter.
Getting Server Reference
- MongoClient client = new MongoClient(connectionString);
- MongoServer server = client.GetServer();
The code above gets a reference of Mongo server, it calls the GetServer() function of the Mongo client that returns objects of the Mongo server.
Getting Database ReferenceTo 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");
This code calls the GetDatabase function to get a reference of the Mongo databse. The Get Database function takes the name of the server as a parameter. If the database is not available then MongoDB creates a database with a specified name in the parameter and returns the database. Here the code is trying to get a reference of the test database.
Getting Reference of CollectionLike 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");
The getcollection function takes a symbol name as parameter and returns a reference of the collection. Like the Get Database function, the Get Collection function also creates a collection. If a collection is not available then the specified name is the parameter. Here the symbol is an entity that specifies the type of collection.
Getting Reference of Collection ListA 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();
Drop Collection from Database
- MongoClient client = new MongoClient(connectionString);
- MongoServer server = client.GetServer();
- MongoDatabase database = server.GetDatabase("Test");
- database.DropCollection("Symbols");
The Drop Collection function of the Mongo database class deletes a collection specified by the name in the parameter from the database.
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);
Symbol is a class, the code above inserts an object of a symbol into the collection. In the following you would have noticed id which is of type ObjectID. Property id is not specified in the code above because this is optional, if you do not specify a MongoDB collection then, like a SQL table, it automatically gives an id number to it. Like an auto-generated id column in a SQL Server table.
- public class Symbol
- {
- public string Name { get; set; }
- public ObjectId ID { get; set; }
- }
Querying form Collection
Querig list of data
- MongoCollection symbolcollection= database.GetCollection<Symbol>("Symbols")
- List< Symbol > query = symbolcollection.AsQueryable<Symbol>().Where<Entity>(sb => sb.Name == "Star").ToList();
Same as queryig a sigle data
- Symbol symbol = symbolcollection.AsQueryable<Entity>().Where<Entity>(sb => sb.Name == "Kailash").SingleOrDefault();
Saving Data into Collection
- MongoCollection symbolcollection= database.GetCollection<Symbol>("Symbols")
- Symbol symbol = symbolcollection.AsQueryable<Entity>().Where<Entity>(sb => sb.Name == "Kailash").SingleOrDefault();
- symbolcollection.Save(symbol);
The save function of MongoDB collection saves an existing document.
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 DataAn 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");
- symbolcollection.Update(query3, update);
Removing Data From CollectionTo 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);
To remove all the data from collection:
- symbolcollection.RemoveAll();
Full Code