Basics of MongoDB with .Net

Basics of MongoDB with .Net

Watch the “Introduction to MongoDB”

Download MongoDB for Windows 64bit:

Unzip to C:Mongo

Follow these instructions for installation:

Run these two applications (can be setup as a Windows Service)

  1. Mongod.exe first (which will stay open)
  2. Mongo.exe second, which will run and connect to Mongod.exe


Now connect to your Test database:

  1. Open a command prompt.
  2. Browse to c:Mongobin
  3. Type: mongod
  4. Make sure you leave this running (this is your database server)


Alternatively you can create a shortcute with:

Target: C:WindowsSystem32cmd.exe /k mongod

Start in: C:Mongobin

Create your first document:

  1. Open a new command prompt.
  2. Browse to c:Mongobin
  3. Type: mongo (this connects you to the database server running locally)
  4. Type: db and hit enter to see what database you’re connected to.
  5.{a:1}) (inserts a document)
  6. Type: (does a search on the document database)


.Net Setup for MongoDB

Download drivers for MongoDB C# and .Net.

MongoDB C# driver MSI:

Download and run.

Community supported driver:

Download to C:MongoCommunityCSharpDriver

You can drop the 3 .DLLs into your .Net project.




.Net Sample Web Application

Create a new web application in Visual Studio 2010 (or 2008)

Add the 3 reference DLLs.

Create/Open a Default.aspx.cs file and connect to your test Mongo Database:

Drop some controls on (I’m using Telerik’s RadGrid in this example)

    <form id="form1" runat="server">
            Create a new Mongo Database:<br />
        <asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
&nbsp;<asp:Button ID="Button1" runat="server" onclick="Button1_Click" Text="Create" />
        <br />
        <br />
        <asp:Button ID="Button2" runat="server" onclick="Button2_Click" 
            Text="View Results" />
        <br />
        Results<telerik:RadGrid ID="RadGrid1" runat="server">

    <telerik:RadScriptManager ID="RadScriptManager1" Runat="server">


Add some code:

        protected void CreateMongoDB(String dbName)
            //mongod.exe must be running for this to work.
            var mongo = new Mongo();

            //if the database is not found in c:datadb it will be created.
            var db = mongo.GetDatabase(dbName);

            //declare a new "table"
            var categories = db.GetCollection("categories");

            //create a new key value set
            var document = new Document();
            document["Name"] = "Product";
            document["Name"] = "Price";

            //create the "tabt"


And the button call:

        protected void Button1_Click(object sender,EventArgs e)
            String name = TextBox1.Text;


Run it.

Now you can create MongoDB’s through a web form.

Filling a Grid with the Results

We’ll jump ahead a tiny bit to where you’ve added some documents to one of your MongoDB’s.

Mine is called TestProducts.

Each document has a Name and a Price.

Add some more code to default.aspx.cs

        protected String GetMongoDBResults(String dbName)
            //mongod.exe must be running for this to work.
            var mongo = new Mongo();

            //if the database is not found in c:datadb it will be created.
            var db = mongo.GetDatabase(dbName);

            //declare a new "table"
            var categories = db.GetCollection("categories");

            //get the categories table
            var category = categories.FindOne(new Document() { { "Name","Price" } });
            //alternatively you can get all documents in the database
            var documents = categories.FindAll().Documents;
            String res = category["Name"].ToString();


            //return results in a EF friendly shapre just because that's what I'm working with mostly nowadays
            return res;


Add the button call code:

        protected void Button2_Click(object sender,EventArgs e)
            RadGrid1.DataSource = GetMongoDBResults(TextBox1.Text);


Run it.

Now you can fill a Grid with data from your MongoDB.

Twitterizer & .Net: Adding a feed to your website

Create a Twitter user:

Register your application:
This gives you:
    <add key=”AccessToken” value=”blahblahblah”/>
    <add key=”AccessTokenSecret” value=”blahblahblah”/>
    <add key=”ConsumerKey” value=”blahblahblah”/>
    <add key=”ConsumerSecret” value=”blahblahblah”/>
Add it to your web.config

Go to:
Download the Twitterizer package:

Twitterizer2.dll and Newtonsoft.Json.dll
in your project references

Make an ASPX page with:
                    <div id=”homeDev”>
                        <fieldset style=”width: 230px”>
                            <legend>Development Buzz</legend>

Do this in the .CS
 public partial class Home : System.Web.UI.Page
        private string _data1;
        public string Data1
            get { return _data1; }
            set { _data1 = value; }
        protected void Page_Load(object sender, EventArgs e)

        protected void ConnectTwitter()
            OAuthTokens tokens = new OAuthTokens();
            tokens.AccessToken = ConfigurationManager.AppSettings[“AccessToken”];
            tokens.AccessTokenSecret = ConfigurationManager.AppSettings[“AccessTokenSecret”];
            tokens.ConsumerKey = ConfigurationManager.AppSettings[“ConsumerKey”];
            tokens.ConsumerSecret = ConfigurationManager.AppSettings[“ConsumerSecret”];
            TwitterResponse<TwitterStatusCollection> statuses = TwitterTimeline.HomeTimeline(tokens);
            for (int i = 0; i < statuses.ResponseObject.Count; i++)
                Data1 += “<p>”;
                Data1 += statuses.ResponseObject[i].Text.ToString();
                Data1 += “</p>”;

© Copyright Duke Hall - Designed by Pexeto