Getting Started
The MongoDB.sln requires Visual Studio 2010 Beta 2, available on msdn. The driver library is named MongoDB.dll and has no other dependencies.
using System;
using MongoDB; // mongo-clr4-driver
namespace MongoSample
{
class Program
{
static void Main(string[] args)
{
var mongo = new Mongo();
foreach (var db in mongo.GetDatabaseNames())
{
Console.WriteLine(string.Format("{0}:", db));
foreach (var col in mongo.GetDB(db).GetCollectionNames())
{
Console.WriteLine("\t\t" + col);
}
}
}
}
}
The Doc
is the document data container. It is essentially an IDictionary<string, object>
with a couple Mongo specific features. In fact, you can insert any class implementing IDictionary<string, object>
into a Collection
but you will always get a Doc
back from a collection.FindOne()
. The literal syntax for dictionaries in C# makes creating Docs in code fairly clean, though not as clean as Ruby or Python.
var post = new Doc {
{"author", "Washington Irving"},
{"title", "On the paradox of Catch-22"},
{"pubdate", DateTime.UtcNow},
{"body", "lorem ipsum ..."},
{"tags", new [] {"literature", "reviews", "random"}}
};
mongo.blog.posts.Insert(post);
or using dynamic dispatch:
dynamic post = new Doc();
post.author = "Washington Irving";
...
post.tags = new [] {"literature", "reviews", "random"};
mongo.blog.posts.Insert(post);
One cool aspect of .Net 4 is the dynamic
keyword. For example, if I have a database named blog with a collection named posts, I could print the author of each post like this:
dynamic mongo = new Mongo();
foreach(var post in mongo.blog.posts.Find())
{
Console.WriteLine(post.author);
}
- Mongo
- can use
m.<dbname>
instead ofm.GetDB("<dbname>")
- can use
- Database
- can use
db.<collectionName>
instead ofdb.GetCollection("<collectionName>")
- can use
- Collection
- can use
coll.<subCollection>
instead ofcoll.Database.GetCollection("<collectionName>.<subCollection>")
- can use
- Doc
- can use
doc.<key>
anddoc.<key> = value
instead ofdoc["<key>"]
anddoc["<key>"] = value
- can use
GridFS support is provided in the MongoDB.GridFS
namespace as an extension to the MongoDB.Collection
class with full System.IO.Stream
access. This example adds a new image to the images database from the local file system.
using System;
using System.IO;
using MongoDB;
using MongoDB.GridFS;
namespace MongoSample
{
class Program
{
static void Main(string[] args)
{
var mongo = new Mongo();
var gridfs = mongo.GetDB("images").GridFS();
var newImage = gridfs.GetFile("summer-vacation.jpg");
newImage.ContentType = "image/jpeg";
using (var gridStream = newImage.Open(FileAccess.Write))
using (var source = File.Open(@"C:\summer.jpg", FileMode.Open, FileAccess.Read))
{
source.CopyTo(gridStream);
}
}
}
}
Unfortunately, extension methods don’t work with the dynamic
keyword, so when using GridFS extensions remember to use static types.
see IronPython