
How to Use MongoDB with C#
MongoDB is one of many NoSQL databases today and that fits perfectly where the relationship complexity is less or none between tables. Because of no relationship and schemaless structure, it provides fast results. So, let’s start gathering tools to use MongoDB with C#.
Requirement:
- MongoDB Server – Download server and install it as a service so that it will always run in the background. Link to download: https://www.mongodb.com/download-center/community
- Mongocsharp.linqindexers – It is a driver by 10gen Inc, to connect MongoDB with .Net. You can install it from the NuGet package manager.
- NoSqlBooster – It is a tool just like SSMS or MySql WorkBench for MongoDB, which you can download it from this link: https://nosqlbooster.com/downloads.
The third requirement is optional. You can use the tool to check MongoDB storing. In the MongoDB collection refers to a table while a document refers to a row of table in RDBMS.
After we have collected all the necessary tools, we can start with coding.
Add the lines below in your webconfig file:
<connectionStrings>
<add name=”mongoDB” connectionString=”server=127.0.0.1; database=testdb” />
</connectionStrings>
The database name provided here will be your database name and MongoDB will automatically create a DB if it doesn’t exist.
The next step is to create a generic helper class which will allow us to make a connection with our database and return collection.
MongoHelper.cs
public class MongoHelper<T> where T : class
{
public MongoCollection<T> Collection { get; private set; }
public MongoHelper()
{
MongoConnectionStringBuilder con = new MongoConnectionStringBuilder(ConfigurationManager.ConnectionStrings[“mongoDB”].ConnectionString);
MongoClient client = new MongoClient(MongoClientSettings.FromConnectionStringBuilder(con));
MongoServer server = new MongoServer(MongoServerSettings.FromClientSettings(client.Settings));
MongoDatabase db = server.GetDatabase(con.DatabaseName);
Collection = db.GetCollection<T>(typeof(T).Name.ToLower());
}
}
After this is completed, we can use this helper class wherever necessary to perform operations on the collection.
Let’s look at Student class which is also our collection in MongoDB to perform basic database operations.
Student.cs
public class Student
{
private readonly MongoHelper<Student> _student;
[BsonId]
[BsonRepresentation(BsonType.ObjectId)]
public string StudentId { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
public string ClassName { get; set; }
public string RollNo { get; set; }
………
public string CreatedDate { get; set; }
public string UpdatedDate { get; set; }
public Student() { _student = new MongoHelper<Student>(); }}
In Student class there are two things that can be noted:
- StudentId attribute is marked with MongoDB BsonId attribute, that means MongoDB will treat it as unique key otherwise it will itself create a field “_id” of type ObjectId as a unique key in student collection.
- In constructor, the MongoHelper class that we created earlier will return the student collection from the database.
Now we can perform the data manipulation on the collection. Some examples are given below:
Insert Data
public void Create(Student student)
{
_student.Collection.Save(student);
}
Update Data
public void Update(Student newStudent)
{
var query = Query<Student>.EQ(x => x.StudentId, newStudent.StudentId);
var set = Update<Student>.Set(x => x.FirstName, newStudent.FirstName);
_student.Collection.Update(query, set);
}
Delete Data
public void Delete(string studentId)
{
var query = Query<Student>.EQ(x => x.StudentId, studentId);
_student.Collection.Remove(query);
}
Get Data
public List<Student> GetAll(string studentId)
{
var query = Query<Student>.EQ(x => x.StudentId, studentId);
return _student.Collection.Find(query).ToList();
}
Summary
In this illustration we learned about how to connect MongoDB with C# and perform different data manipulation on its collection.
If you have questions about MongoDB contact Dignitas Digital in Philadelphia by sending an email to hello@dignitas.digital .