Using Linq with MongoDB

Last week we looked at accessing MongoDB using the C# driver. This week we will look at accessing it using Linq.

If you followed the instructions for last weeks post, you already have everything you need to get up and running. So lets just jump right in.

Referencing MongoDB.Linq

To access the Linq functionality of the MongoDB C# driver, you need to add a reference to the MongoDB.Linq.dll which comes in the distribution with the C# driver. Simply add a reference to it.


Write the Linq Code

Next we want to replace the query code from last week with the Linq query code. So find the following code in last week’s Program.cs file.

// Create a specification to query the orders collection.
var spec = new Document();
spec["customerName"] = "Elmer Fudd";

// Run the query.
Document result = orders.FindOne( spec );

And replace it with this code…

// Query the orders collection.
var results =
	from doc in orders.AsQueryable()
	where doc.Key( "customerName" ) == "Elmer Fudd"
	select doc;
var result = results.FirstOrDefault();

The IMongoCollection interface exposes the AsQueryable() method which gives you access to all the Linq goodness.

I realize this was a very short post this week, but that is more a testament to the ease of use than to the laziness of the blogger.

Next week we’ll dig deeper into querying the db.


This entry was posted in .NET, C#, Linq, MongoDB, NoSQL and tagged , , , , . Bookmark the permalink. Post a comment or leave a trackback: Trackback URL.

Post a Comment

Your email is never published nor shared. Required fields are marked *

You may use these HTML tags and attributes <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>