Getting Started

collinsauve edited this page Sep 24, 2010 · 5 revisions
Clone this wiki locally

Getting Started

1) Configuration

MongoDB-CSharp does not require any configuration to work. By default, it will connect to your localhost MongoDB server. Most likely, however, you will need to make some changes. We support overriding the behaviour of virtually every part of MongoDB-CSharp, but choose some sensible defaults so you won’t have to. See Configuration for details on how to customize MongoDB-CSharp. The rest of “Getting Started” will assume the configuration was left alone and all the defaults are used.

2) Connecting

Connect to a Mongo server running on localhost and the default port.

  Mongo mongo = new Mongo();
  mongo.Connect();

3) Database

Through a single Mongo object, you can connect to all the database on your server, or even one that doesn’t exist. Because of the way MongoDB works, the database will get created the first time you use it. Subsequent uses will use the one that already exists.

var db = mongo.GetDatabase("db_name");

4) Collections

Collections work in the same way databases work. It will get created the first time it is used. Subsequent uses will use the one that already exists.

MongoDB-CSharp supports both unstructured collections (Document Collections) and structured collections (Typed Collections). Document Collections are useful when your schema is loosely defined(unknown) and/or change is unpredictable. Typed Collections are useful when a schema is well-defined and/or change is predictable.

Document Collections

Documents are an unstructured schema object that is essentially a wrapped version of a Dictionary<string, object>. It has some useful methods that make it easier to work with than the standard Dictionary<string, object>.

A simple query to pull all the documents out of a collection:

  ICursor<Document> cursor = mongo["database_name"]["Person"].FindAll();
  foreach(Document document in cursor.Documents)
  {            
    //do something with the document
  } 

To enable filters on the query, it simply needs to be specified in the Find method call. In the below example, we will be filtering out all people that are younger than 18.

  ICursor<Document> cursor = mongo["database_name"]["Person"].Find(new Document("Age", Op.GreaterThanOrEqual(18)));
  foreach(Document document in cursor.Documents)
  {
    //do something with the document
  }

Typed Collections

Alternatively, you can use Typed Collections. Typed collections will read your class and use its structure to query a Mongo collection and hydrate the entities with the results.

A simple query to pull all the people out of a collection:

  ICursor<Person> cursor = db.GetCollection<Person>("Person").FindAll();
  foreach(Person person in cursor.Documents)
  {
    //do something with the person
  }

To enable filters on the query, it simply needs to be specified in the Find method call. In the below example, we will be filtering out all people that are younger than 18.

  ICursor<Person> cursor = db.GetCollection<Person>("Person").Find(new { Age = Op.GreaterThanOrEqual(18) });
  foreach(Person person in cursor.Documents)
  {
    Console.WriteLine(person.FirstName);
  }

For more on querying, see the mongodb-spec.

Linq

Both the above query types suffer the same problem. A refactoring of the code might cause them to break, and you wouldn’t know until runtime. For instance, in the above example, the “Age” property was used. If we rename Age, or remove it completely, then we would not get compile time errors at all. This will always continue to be a problem with Document Collections, but Typed Collections, when using Linq, will get compile time safety and refactoring support. Therefore, when possible, it is always advisable to use the Linq query capabilities.

Both Document and Typed Collections support Linq based queries. This is probably the easiest way to query collections as it is a natural fit for .NET developers. See Linq for more details.

Below, you can see 2 examples of using linq to filter out all people that are younger than 18.

With Document Collections:

  IEnumerable<Document> docs = db.GetCollection("Person").Find(doc => (int)doc["Age"] >= 18);
  foreach(Document doc in docs)
  {
    //do something with doc
  }

With Typed Collections:

  IEnumerable<Person> people = db.GetCollection<Person>("Person").Find(x => x.Age >= 18);
  foreach(Person person in people)
  {
    //do something with person
  }

5) Persistence

TODO: