CodeProject
Among NoSQL databases, MongoDB is very popular. For those who need an introduction, MongoDB is an open sourced document database providing high performance, availability, and automatic scaling. Being a document database, a record/row in MongoDB is know as document. The data structure of a document is similar to JSON object, having key and value pairs. A key is a string
, whereas the value can be a string
/ number/ another document/ arrays/ arrays of documents. A document looks like this:
CodeProject
{
EmpName: "Bibhu",
Age: 25,
Sex: "M"
Department: 10
}
When we group documents, a collection is formed. A collection is synonymous to a table in relational database. A collection exists within a single database. Collections do not enforce a schema, that means documents within a collection can have different fields. MongoDB uses dynamic schemas. We can create collections without defining the structure, i.e., the fields or the types of their values, of the documents in the collection and also can change the structure of documents simply by adding new fields or deleting existing ones. All documents stored in a collection require a unique “_id
” field that acts as a primary key. It gets automatically added to a document if we do not specify. With this much knowledge, we are good to go.
Before we start, we need to download MongoDB. We can refer the quick start instructions to install it. In order to start the MongoDB server, we need to execute the “mongod.exe” executable, from the command prompt. Assuming, the extraction is done in the C drive, the command is:
C:\mongodb\bin\mongod.exe --dbpath d:\mongodb\data
MongoDB is self-contained and does not have any other system dependencies. Hence, we can run MongoDB from any folder in any drive. One thing to note here is the “–dbpath
” option. MongoDB requires a data folder to store its files, being a document database. “–dbpath
” option provides a way to specify an alternative location of MongoDB’s data file storage. Over here, we are storing in “d:\mongodb\data”. The default location for the MongoDB data directory is “C:\data\db” . So we can also start “mongod.exe” executable, from the command prompt, if we have “C:\data\db” already present.
C:\mongodb\bin\mongod.exe
The “waiting for connections” message in the console output indicates that the “mongod.exe” process is running successfully.
To use MongoDB in our webform application, we need the MongoDB C# driver which is available as a NuGet package. Upon installation, it adds reference to two libraries, “MongoDB.Bson.dll” and “MongoDB.Driver.dll”.
After installation, we can get the running MongoDB client and a reference to the sever, in our code in this manner :
String connectionString = "mongodb://localhost";
MongoClient client = new MongoClient(connectionString);
MongoServer server = client.GetServer();
Now we have the server, we need to find out the db and the collection against which we will be running our queries.
MongoDatabase database = server.GetDatabase("mydb"); MongoCollection<EmpInfo> _employees =
database.GetCollection<EmpInfo>("emp");
We have created our own domain class “EmpInfo
” to work with the “emp
” collection. All three properties, having the same name as that of column name. “_id
” is of BSON “ObjectId
” type, but we can have other type also. It acts as the primary key and is unique for the document. For operations where we do not explicitly specify a value for the “_id”
field, MongoDB creates a unique “ObjectId
” value for the field before inserting it into the collection.
public class EmpInfo
{
public ObjectId _id { get; set; }
public string empName { get; set; }
public string dept { get; set; }
}
Projection
In order to display all of the documents present in the collection, we can loop through the “_employees
” collection.
foreach (EmpInfo employee in _employees.FindAll())
{
}
Insertion
To insert a document to the collection:
_employees.Insert(new EmpInfo{ empName = "Tom", dept = "Sales"});
var id = entity.Id;
Updation
In order to update a document, we need to find the existing document, we can do so in this way:
var query = Query<EmpInfo>.EQ(e => e.empName, "Tom");
Here, we are assuming that the search will be based on the “empName
” column, provided by the user. After getting the document, we can update it in this manner:
var update = Update<EmpInfo>.Set(e => e.dept, "Sales");
_employees.Update(query, update);
An alternative to “Update()
” is “Save()
”. The difference is that “Save()
” sends the entire document back to the server, but “Update()
” sends just the changes.
var query = Query<EmpInfo>.EQ(e => e.empName, "Tom");
var document = _employees.FindOne(query);
document.dept = "Sales";
_employees.Save(document);
Deletion
To remove an existing document, we can achieve it in this manner:
var query = Query<EmpInfo>.EQ(e => e.empName, "Tom");
_employees.Remove(query);
One thing to note over here, is nowhere we are opening or closing a connection. This is taken care of by the driver itself, which uses a connection pool to use connections to the server efficiently.
You can download the demo files from here.