Archived Support Site

This support site is archived. You can view the old support discussions but you cannot post new discussions.

Using MongoDB

The AppHarbor add-on catalog has two great MongoDB add-ons, MongoHQ and MongoLab. When you provision a MongoDB add-on, you can fetch the Mongo url from the appSettings section of your web.config. The setting we inject is called MONGOHQ_URL or MONGOLAB_URI depending on what add-on you have
chosen.

Using MongoDB from a .NET is simple. There are a bunch of .NET drivers around, but for this example, we will use standard driver maintained and supported by 10gen (the makers of MongoDB).

The driver can be added to your project using NuGet:

install-package mongocsharpdriver

10gen has a detailed tutorial, but here are some basics.

The objects you persist to MongoDB have to be instances of classes that have an Id member, like this one (Bson is a binary serialization of JSON):

using MongoDB.Bson;

namespace AppHarborMongoDBDemo.Models
{
    public class Thingy
    {
        public ObjectId Id { get; set; }
        public string Name { get; set; }
    }
}

You can persist and fetch objects of this class like so:

var connectionstring =
    ConfigurationManager.AppSettings.Get("(MONGOHQ_URL|MONGOLAB_URI)");
var url = new MongoUrl(connectionstring);
var client = new MongoClient(url);
var server = client.GetServer();
var database = server.GetDatabase(url.DatabaseName);

var collection = database.GetCollection<Thingy>("Thingies");

// insert object
collection.Insert(new Thingy { Name = "foo" });

// fetch all objects
var thingies = collection.FindAll();

If you are testing with a local instance of MongoDB, your connection URI should look something like this:

"mongodb://localhost/Things";

We have created a complete MVC app using MongoDB that you can use to get started.

For more information about MongoDB like queries, upserts, geospatial queries, and high performance indexes, see: http://www.mongodb.org/display/DOCS/Home