How to read, add, update, delete records in MongoDB using C#

In this post, I will show how to perform basic database operations in MongoDB using C# in your .Net applications. In this post I will focus on four simple operations showing following:

  • How to add new record in MongoDB
  • How to read records in MongoDB
  • How to update records in MongoDB
  • How to delete record in MongoDB

For all the code snippets that I will show for each of these operations, I have the following set up in my server.

Database Name: Commerce
Table Name: Roles
Role object is defined as shown below:
public class Role
{
    public ObjectId Id { get; set; }
    public string Name { get; set; }
    public string Description { get; set; }
    public DateTime? CreateDate { get; set; }
    public DateTime? LastUpdateDate { get; set; }
}

Add new record in MongoDB

Use Insert method on MongoCollection object.

public void AddRole(Role role)
{
    try
    {
        var db = this.DatabaseConnector.GetDatabase("Commerce");
        var roles = db.GetCollection<Role>("Roles");
        roles.Insert(role);
    }
    catch (Exception ex)
    {
        System.Diagnostics.Debug.WriteLine(ex.Message);
        throw;
    }
}

Read records from MongoDB

To read records from MongoDB, there are multiple ways to get cursor to read the records. And part of these operations is to specify your search criteria as well. In this code sample I am just going to show how to read all records form a table or collection in MongoDB.

public IQueryable<Role> GetAllRoles()
 {
     try
     {
         var db = this.DatabaseConnector.GetDatabase("Commerce");
         var roles = db.GetCollection<Role>("Roles");
         return roles.AsQueryable();
     }
     catch (Exception ex)
     {
         System.Diagnostics.Debug.WriteLine(ex.Message);
         throw;
     }
 }

How to update records in MongoDB

To update a record in MongoDB using C#, you can use Save method on MongoCollection object.

public void UpdateRole(Role role)
{
    try
    {
        var db = this.DatabaseConnector.GetDatabase("Commerce");
        var roles = db.GetCollection<Role>("Roles");
        var existingRole = FindRole(role.Name);
        if (null != existingRole)
        {
            existingRole.Name = role.Name;
            existingRole.Description = role.Description;
            existingRole.LastUpdateDate = role.LastUpdateDate;
        var result = roles.Save(existingRole);
            System.Diagnostics.Debug.WriteLine(result.Ok);
        }
    }
    catch (Exception ex)
    {
        System.Diagnostics.Debug.WriteLine(ex.Message);
        throw;
    }
}

Save method returns an instance of WriteConcernResult. This object contains the information about outcome of save operation. There are some important properties of this object that can tell you if record update worked or not.

  • DocumentaAffected: This property will have count of numbers affected by the operation. If your update worked, then this value be a non-zero positive value corresponding to numbers of records that you tried to update. If this number is ZERO then we have a problem.
  • UpdatedExisting: This value indicates if an existing record was affected. If you are updating existing record by calling Save method, then this property must be set to true.
  • HasLastErrorMessage: This property will tell you if there was an error during the operation. If there was an error then you can check LastErrorMessage property to find out the exact error.
  • Ok: Check value of this property to check if there was any error during the command. If this value is true, that means that command was successful.

Delete records in MongoDB

You can use Remove method on MongoCollection object to remove a record. Unlike entity framework, you will have to pass a query to this command telling the where clause that is going to be used to find the result that is going to be deleted.

public void DeleteRole(string roleName)
{
    try
    {
        var db = this.DatabaseConnector.GetDatabase("Commerce");
        var roles = db.GetCollection<Role>("Roles");
        var query = Query.EQ("Name", roleName);
        var result = roles.Remove(query);
    }
    catch (Exception ex)
    {
        System.Diagnostics.Debug.WriteLine(ex.Message);
        throw;
    }
}

Remove method will return WriteConcernResult that can be checked to see if record was deleted or not.

Search

Social

Weather

23.3 °C / 73.9 °F

weather conditions Clouds

Monthly Posts

Blog Tags