How to work with MongoDB in .Net


MongoDB is a popular, open source, scale-out NoSQL database that provides high throughput for your data-driven applications. Unlike relational databases such as SQL Server, Oracle, and MySQL, which store data in tables according to a rigid schema, MongoDB stores data in documents with flexible schema. There are many such non-relational databases around including CouchDB, RavenDB, and Couchbase. However, I like MongoDB primarily due to its scalability, speed, and dynamic querying capabilities.

MongoDB uses the BSON format under the hood to represent the JSON documents at the heart of the data store. BSON or “Binary JSON” is a lightweight and efficient binary-encoded data serialization format that supports fast data traversal and searches. BSON also allows MongoDB to support data types—namely int, long, date, floating point, and decimal128—not represented in JSON. 

In MongoDB documents are part of collections, in much the same way as a row is part of a table in a relational database. A document is essentially a collection of field and value pairs, which can also be nested. Note that a value in MongoDB can be a document, an array of documents, an array of BSON, or just a BSON type. Let’s look at how we can work with MongoDB using C#. 

Install MongoDB and create a new project

Start by . Unzip the binaries to a folder of your choice in your system and create a separate folder (in my case C:datadb) for the data. Then, to start MongoDB, navigate to the folder where MongoDB is installed and execute the mongod command in the command prompt window. That should start MongoDB at port 27017 by default.