99 Comments

MongoDB version 2.2 was released in late August and the biggest change it brought was the addition of the Aggregation Framework. Previously the aggregations required the usage of map/reduce, which in MongoDB doesn’t perform that well, mainly because of the single-threaded Javascript-based execution. The aggregation framework steps away from the Javascript and is implemented in C++, with an aim to accelerate performance of analytics and reporting up to 80 percent compared to using MapReduce.

The aim of this post is to show examples of running the MongoDB Aggregation Framework with the official MongoDB C# drivers.

Aggregation Framework and Linq

Even though the current version of the MongoDB C# drivers (1.6) supports Linq, the support doesn’t extend to the aggregation framework. It’s highly probable that the Linq-support will be added later on and there’s already some hints about this in the driver’s source code. But at this point the execution of the aggregations requires the usage of the BsonDocument-objects.

Aggregation Framework and GUIDs

If you use GUIDs in your documents, the aggregation framework doesn’t work. This is because by default the GUIDs are stored in binary format and the aggregations won’t work against documents which contain binary data.. The solution is to store the GUIDs as strings. You can force the C# drivers to make this conversion automatically by configuring the mapping. Given that your C# class has Id-property defined as a GUID, the following code tells the driver to serialize the GUID as a string:

BsonClassMap.RegisterClassMap<MyClass>(cm => 
{ 
    cm.AutoMap(); 
    cm.GetMemberMap(c => c.Id) 
      .SetRepresentation( 
          BsonType.String); 
});

The example data

These examples use the following documents:

> db.examples.find()
{ "_id" : "1", "User" : "Tom", "Country" : "Finland", "Count" : 1 }
{ "_id" : "2", "User" : "Tom", "Country" : "Finland", "Count" : 3 }
{ "_id" : "3", "User" : "Tom", "Country" : "Finland", "Count" : 2 }
{ "_id" : "4", "User" : "Mary", "Country" : "Sweden", "Count" : 1 }
{ "_id" : "5", "User" : "Mary", "Country" : "Sweden", "Count" : 7 }

Example 1: Aggregation Framework Basic usage

This example shows how the aggregation framework can be executed through C#. We’re not going run any calculations to the data, we’re just going to filter it by the User.

To run the aggregations, you can use either the MongoDatabase.RunCommand –method or the helper MongoCollection.Aggregate. We’re going to use the latter:

var coll = localDb.GetCollection("examples"); 
... 
coll.Aggregate(pipeline);

The hardest part when working with Aggregation Framework through C# is building the pipeline. The pipeline is similar concept to the piping in PowerShell. Each operation in the pipeline will make modifications to the data: the operations can for example filter, group and project the data. In C#, the pipeline is a collection of BsonDocument object. Each document represents one operation.

In our first example we need to do only one operation: $match. This operator will filter out the given documents. The following BsonDocument is a pipeline operation which filters out all the documents which don’t have User-field set to “Tom”.

var match = new BsonDocument 
                { 
                    { 
                        "$match", 
                        new BsonDocument 
                            { 
                                {"User", "Tom"} 
                            } 
                    } 
                };

To execute this operation we add it to an array and pass the array to the MongoCollection.Aggregate-method:

var pipeline = new[] { match }; 
var result = coll.Aggregate(pipeline);

The MongoCollection.Aggregate-method returns an AggregateResult-object. It’s ResultDocuments-property (IEnumarable<BsonDocument>) contains the documents which are the output of the aggregation. To check how many results there were, we can get the Count:

var result = coll.Aggregate(pipeline); 
Console.WriteLine(result.ResultDocuments.Count());

image

The result documents are BsonDocument-objects. If you have a C#-class which represent the documents, you can cast the results:

var matchingExamples = result.ResultDocuments 
    .Select(BsonSerializer.Deserialize<ExampleData>) 
    .ToList();

foreach (var example in matchingExamples) 
{ 
    var message = string.Format("{0} - {1}", example.User, example.Count); 
    Console.WriteLine(message); 
}

image

Another alternative is to use C#’s dynamic type. The following extension method uses JSON.net to convert a BsonDocument into a dynamic:

public static class MongoExtensions 
{ 
    public static dynamic ToDynamic(this BsonDocument doc) 
    { 
        var json = doc.ToJson(); 
        dynamic obj = JToken.Parse(json); 
        return obj; 
    } 
}

Here’s a way to convert all the result documents into dynamic objects:

var matchingExamples = result.ResultDocuments 
    .Select(x => x.ToDynamic()) 
    .ToList();

Example 2: Multiple filters & comparison operators

This example filters the data with the following criteria:

  • User: Tom
  • Count: >= 2
var match = new BsonDocument 
                { 
                    { 
                        "$match", 
                        new BsonDocument 
                            { 
                                {"User", "Tom"}, 
                                {"Count", new BsonDocument 
                                                   { 
                                                       { 
                                                           "$gte", 2 
                                                       } 
                                                   }} 
                            } 
                    } 
                };

The execution of this operation is identical to the first example:

var pipeline = new[] { match }; 
var result = coll.Aggregate(pipeline);
var matchingExamples = result.ResultDocuments 
    .Select(x => x.ToDynamic()) 
    .ToList();

Also the result are as expected:

foreach (var example in matchingExamples) 
{ 
    var message = string.Format("{0} - {1}", example.User, example.Count); 
    Console.WriteLine(message); 
}

image

Example 3: Multiple operations

In our first two examples, the pipeline was as simple as possible: It contained only one operation. This example will filter the data with the same exact criteria as the second example, but this time using two $match operations:

    • User: Tom
    • Count: >= 2

var match = new BsonDocument 
                { 
                    { 
                        "$match", 
                        new BsonDocument 
                            { 
                                {"User", "Tom"} 
                            } 
                    } 
                };
var match2 = new BsonDocument 
                { 
                    { 
                        "$match", 
                        new BsonDocument 
                            { 
                                {"Count", new BsonDocument 
                                                   { 
                                                       { 
                                                           "$gte", 2 
                                                       } 
                                                   }} 
                            } 
                    } 
                };

var pipeline = new[] { match, match2 };

The output stays the same:

image

The first operation “match” takes all the documents from the examples collection and removes every document which doesn’t match the criteria User = Tom. The output of this operation (3 documents) then moves to the second operation “match2” of the pipeline. This operation only sees those 3 documents, not the original collection. The operation filters out these documents based on its criteria and moves the result (2 documents) forward. This is where our pipeline ends and this is also our result.

Example 4: Group and sum

Thus far we’ve used the aggregation framework to just filter out the data. The true strength of the framework is its ability to run calculations on the documents. This example shows how we can calculate how many documents there are in the collection, grouped by the user. This is done using the $group-operator:

var group = new BsonDocument 
                { 
                    { "$group", 
                        new BsonDocument 
                            { 
                                { "_id", new BsonDocument 
                                             { 
                                                 { 
                                                     "MyUser","$User" 
                                                 } 
                                             } 
                                }, 
                                { 
                                    "Count", new BsonDocument 
                                                 { 
                                                     { 
                                                         "$sum", 1 
                                                     } 
                                                 } 
                                } 
                            } 
                  } 
                };

The grouping key (in our case the User-field) is defined with the _id. The above example states that the grouping key has one field (“MyUser”) and the value for that field comes from the document’s User-field ($User). In the $group operation the other fields are aggregate functions. This example defines the field “Count” and adds 1 to it for every document that matches the group key (_id).

var pipeline = new[] { group }; 
var result = coll.Aggregate(pipeline);

var matchingExamples = result.ResultDocuments 
    .Select(x => x.ToDynamic()) 
    .ToList();

foreach (var example in matchingExamples) 
{ 
    var message = string.Format("{0} - {1}", example._id.MyUser, example.Count); 
    Console.WriteLine(message); 
}

image

Note the format in which the results are outputted: The user’s name is accessed through _id.MyUser-property.

Example 5: Group and sum by field

This example is similar to example 4. But instead of calculating the amount of documents, we calculate the sum of the Count-fields by the user:

var group = new BsonDocument 
                { 
                    { "$group", 
                        new BsonDocument 
                            { 
                                { "_id", new BsonDocument 
                                             { 
                                                 { 
                                                     "MyUser","$User" 
                                                 } 
                                             } 
                                }, 
                                { 
                                    "Count", new BsonDocument 
                                                 { 
                                                     { 
                                                         "$sum", "$Count" 
                                                     } 
                                                 } 
                                } 
                            } 
                  } 
                };

The only change is that instead of adding 1, we add the value from the Count-field (“$Count”).

image

Example 6: Projections

This example shows how the $project operator can be used to change the format of the output. The grouping in example 5 works well, but to access the user’s name we currently have to point to the _id.MyUser-property. Let’s change this so that user’s name is available directly through UserName-property:

var group = new BsonDocument 
                { 
                    { "$group", 
                        new BsonDocument 
                            { 
                                { "_id", new BsonDocument 
                                             { 
                                                 { 
                                                     "MyUser","$User" 
                                                 } 
                                             } 
                                }, 
                                { 
                                    "Count", new BsonDocument 
                                                 { 
                                                     { 
                                                         "$sum", "$Count" 
                                                     } 
                                                 } 
                                } 
                            } 
                  } 
                };

var project = new BsonDocument 
                { 
                    { 
                        "$project", 
                        new BsonDocument 
                            { 
                                {"_id", 0}, 
                                {"UserName","$_id.MyUser"}, 
                                {"Count", 1}, 
                            } 
                    } 
                };

var pipeline = new[] { group, project };

The code removes the _id –property from the output. It adds the UserName-property, which value is accessed from field _id.MyUser. The projection operations also states that the Count-value should stay as it is.

var matchingExamples = result.ResultDocuments 
    .Select(x => x.ToDynamic()) 
    .ToList();

foreach (var example in matchingExamples) 
{ 
    var message = string.Format("{0} - {1}", example.UserName, example.Count); 
    Console.WriteLine(message); 
}

image

Example 7: Group with multiple fields in the keys

For this example we add a new row into our document collection, leaving us with the following:

{ "_id" : "1", "User" : "Tom", "Country" : "Finland", "Count" : 1 }
{ "_id" : "2", "User" : "Tom", "Country" : "Finland", "Count" : 3 }
{ "_id" : "3", "User" : "Tom", "Country" : "Finland", "Count" : 2 }
{ "_id" : "4", "User" : "Mary", "Country" : "Sweden", "Count" : 1 }
{ "_id" : "5", "User" : "Mary", "Country" : "Sweden", "Count" : 7 }
{ "_id" : "6", "User" : "Tom", "Country" : "England", "Count" : 3 }

This example shows how you can group the data by using multiple fields in the grouping key:

var group = new BsonDocument 
                { 
                    { "$group", 
                        new BsonDocument 
                            { 
                                { "_id", new BsonDocument 
                                             { 
                                                 { "MyUser","$User" }, 
                                                 { "Country","$Country" }, 
                                             } 
                                }, 
                                { 
                                    "Count", new BsonDocument 
                                                 { 
                                                     { "$sum", "$Count" } 
                                                 } 
                                } 
                            } 
                  } 
                };

var project = new BsonDocument 
                { 
                    { 
                        "$project", 
                        new BsonDocument 
                            { 
                                {"_id", 0}, 
                                {"UserName","$_id.MyUser"}, 
                                {"Country", "$_id.Country"}, 
                                {"Count", 1}, 
                            } 
                    } 
                };

var pipeline = new[] { group, project }; 
var result = coll.Aggregate(pipeline);

var matchingExamples = result.ResultDocuments 
    .Select(x => x.ToDynamic()) 
    .ToList();

foreach (var example in matchingExamples) 
{ 
    var message = string.Format("{0} - {1} - {2}", example.UserName, example.Country, example.Count); 
    Console.WriteLine(message); 
}

image

Example 8: Match, group and project

This example shows how you can combine many different pipeline operations. The data is first filtered ($match) by User=Tom, then grouped by the Country (“$group”) and finally the output is formatted into a readable format ($project).

Match:

var match = new BsonDocument 
                { 
                    { 
                        "$match", 
                        new BsonDocument 
                            { 
                                {"User", "Tom"} 
                            } 
                    } 
                };

Group:

var group = new BsonDocument 
                { 
                    { "$group", 
                        new BsonDocument 
                            { 
                                { "_id", new BsonDocument 
                                             { 
                                                 { "Country","$Country" }, 
                                             } 
                                }, 
                                { 
                                    "Count", new BsonDocument 
                                                 { 
                                                     { "$sum", "$Count" } 
                                                 } 
                                } 
                            } 
                  } 
                };

Project:

var project = new BsonDocument 
                { 
                    { 
                        "$project", 
                        new BsonDocument 
                            { 
                                {"_id", 0}, 
                                {"Country", "$_id.Country"}, 
                                {"Count", 1}, 
                            } 
                    } 
                };

Result:

var pipeline = new[] { match, group, project }; 
var result = coll.Aggregate(pipeline);

var matchingExamples = result.ResultDocuments 
    .Select(x => x.ToDynamic()) 
    .ToList();

foreach (var example in matchingExamples) 
{ 
    var message = string.Format("{0} - {1}", example.Country, example.Count); 
    Console.WriteLine(message); 
}

image

More

There are many other interesting operators in the MongoDB Aggregation Framework, like $unwind and $sort. The usage of these operators is identical to ones we used above so it should be possible to copy-paste one of the examples and use it as a basis for these other operations.

Links

Comments

Comment by lunettes de soleil pas cher

lunettes de soleil pas cher...

It`s really useful! Looking through the Internet you can mostly observe watered down information, something like bla bla bla, but not here to my deep surprise. It makes me happy..!...

Comment by zophim

Great tutorial, I was just wondering where you got the ToDynamic() function. Which libraries did you use for these examples?

zophim
Comment by Mikael Koskinen

Hey zophim and thanks for the comment.


The ToDynamic-function is shown in the first example but I've just noticed a problem with it where the datetimes returned from the server aren't handled properly. So I wouldn't use this just yet in the production :)


public static class MongoExtensions { public static dynamic ToDynamic(this BsonDocument doc) { var json = doc.ToJson(); dynamic obj = JToken.Parse(json); return obj; } }


Comment by net grid

Its very nice tutorial .Its very helpful an informative.dapfor provide good tutorial you can reafd from dapfor. com

net grid
Comment by Anony

Great tutorial but there's a display problem with this page, it seems the   html entites have been encoded. (Chrome 23)

Anony
Comment by Mikael Koskinen

Thanks for the comments. It took too long but the problem with the html entities mixed in the code is now fixed.


Sorry for the problems.

Comment by Dmitry

Mikael, thank you for this post -- clear and useful.

Dmitry
Comment by Mark Gibaud

Nice article - allowed me to get up and running with Aggregation in C#. However, new BsonDocument{} this that is verbose and unfriendly code to write - do we know of any tools to abstract this away? Maybe the 10gen C# driver roadmap?

Mark Gibaud
Comment by Mark Gibaud

...this is the best I could come up with:
const string group = @"{$group: { _id: {Pid:'$PageId'}, sharecount : {$sum:1}}}";
const string sort = @"{$sort: {sharecount:-1}}";
const string limit = @"{$limit: 3}";
var des = new Func(MongoDB.Bson.Serialization.BsonSerializer.Deserialize);
return new[] { des(group), des(sort), des(limit)};

Mark Gibaud
Comment by Mark Gibaud

...this is the best I could do:


public static IEnumerable PagesMostViewedAggregationQuery()
{
const string @group = @"{$group: { _id : { Pid: '$PageId'}, pageviews: {$sum : 1}}}";
const string sort = @"{$sort: {pageviews:-1}}";
const string limit = @"{$limit: 3}";
var des = new Func(MongoDB.Bson.Serialization.BsonSerializer.Deserialize);
return new[] { des(group), des(sort),des(limit) };
}

Mark Gibaud
Comment by Mongo | Pearltrees

[...] MongoDB Aggregation Framework Examples in C# - Mikael Koskinen [...]

Comment by oakley sunglasses cheap

oakley sunglasses cheap...

if you want the best bang for your buckcheck out our 100 dozen hot seller's oakley cheap sunglasses packages...

Comment by Oakley Lens Tints

Oakley Lens Tints...

and are found regularly being sold in street marketsless reputable stores and even on the street Fake Oakleys Fake Oakley Sunglasses micheal kors bags sale corners...

Comment by cheap kobe 8

cheap kobe 8...

MongoDB Aggregation Framework Examples in C# - Mikael Koskinen efqeboqucxc kobe 8 for sale...

Comment by Jordan 11 Legend Blue

Jordan 11 Legend Blue...

MARY BISHOP and SHARON BALDWIN, Plaintiffs Appellees, and SUSAN G. BARTON and GAY E. PHILLIPS, Plaintiffs Appellees/ Cross Appellants, v. SALLY HOWE SMITH, in her official capacity as Court Clerk for Tulsa County, State of Oklahoma, Defendant Appellant...

Comment by sprot blue6s

sprot blue6s...

If you like, you can add the optional ingredients to the steak mixture before serving.. The judge did rule on the first part of that hearing, on the contract issues. You should be offered the option of having a chaperone to sit or stand beside you if y...

Comment by Jordan 6 Black Infrared

Jordan 6 Black Infrared...

Starting at Civic Square right next to the Statue of Ethos (12:30pm sharp) close to ACT Legislative Assembly, the bicycle plan is to cycle in a peaceful manner along to Parliament House for the distance of roughly 3kms. There be megaphones speeches, of...

Comment by jordan 4 toro bravo

jordan 4 toro bravo...

3. Oakland, Calif. The old port city across the bay from San Francisco seems to have a lot of fans. It was recently voted America most exciting city. It isn known why Oakland is so popular and was a bit of a surprise for us. Perhaps there are far more ...

Comment by jordan 9 barons

jordan 9 barons...

There's also more choice in the e reader and notebook categories. Amazon has the Kindle 2 (US$260) and the big screen Kindle DX (US$490) at 9.7 inches. But there's also Barnes and Noble's impressive looking new e reader, the Nook (US$260), which fea...

Comment by sport blue 3s

sport blue 3s...

None of them are equipped to house protesters forever."It's a lot of wear and tear on the space," said Michael Ellick, a minister at Judson Memorial Church, which housed protesters for several nights in November. "We're broke, so we don't have a ...

Comment by jordan 11 Legend Blue

jordan 11 Legend Blue...

its general management, operations, finance and manufacturing. The OS X suite...

Comment by sport blue 6s

sport blue 6s...

So Gruber gets into the National Reserve and steals all the gold using the 14 trucks, forcing McClane to go after him. Razer introduced the gaming keypad featuring cutting edge ergonomics, tournament grade controls, extreme customizability, and maximum...

Comment by cheap jordans online

cheap jordans online...

"I thought it was a very important day in my career. 27), the site where the Penguins hoisted the Stanley Cup just three months earlier. We knew it was in good hands, so we split.. I'm listening to Eminem. There is no fracking in Connecticut. DHL Chi...

Comment by jordan 11 low concord

jordan 11 low concord...

I certainly can not know what Mr. Pratt intentions were with the teaching of Joseph Smith post life spirit world. I can say, however, that it was obviously a poor effort to make improvements on the Catholic and Protestant versions of it. Leaving still ...

Comment by pre order new jordans

pre order new jordans...

What is too much meditation? J Krishnamurti once said, quite rightly, that true meditation must be 24 hours a day. By this, he meant that a person should be "self aware" at all times. An hour or two of meditation becomes like a spa retreat, a little ...

Comment by cheap jordan shoes

cheap jordan shoes...

While working for a moving company near her hometown of Smyrna, Georgia, she was asked to leave the home of a client who felt nervous that Chandlers skin would somehow affect the materials she was helping to pack. "I had played with Dravid before [in ...

Comment by jordan 13 hologram

jordan 13 hologram...

It's no secret that Nokia's presence in the North American smartphone market is nonexistent. that's one reason Nokia partnered with Microsoft. But when Nokia brings its first Windows Phone 7 handsets to market in a year or so, solid relationships wi...

Comment by jordan 3 for sale

jordan 3 for sale...

before they are all let loose over 4,000,000, Geo....

Comment by jordan 10 powder blue

jordan 10 powder blue...

So the consumer electronics retailer decided to look outside for a fix outside. It hired French turnaround expert Hubert Joly as CEO in August 2012. Since then, Best Buy has cut jobs, changed store layouts and implemented a price matching policy to com...

Comment by jordan 11 low infrared 23

jordan 11 low infrared 23...

News reports say at least 10 people were arrested says she was within a group of about seven people who were taken into custody in what she called "snatch and grabs," a tactic similar to the police bureau's response to a Tahrir Square solidarity mar...

Comment by jordans for sale

jordans for sale...

I am starting a facebook page for my online writing. I will be posting stuff from my Blog, InfoBarrel and Squidoo. I dont want to use my real name, but most people call it their blog names and work from that. Should. Although 13 is the legal age accord...

Comment by jordans for women

jordans for women...

My goal is to simplify politics and social issues for people who do not have a lot of extra time for reading and research but want to be aware of what's going on. I like short hubs and I cannot lie. Funny if you know what song I'm rifting on . . No d...

Comment by jordan 5 oreo

jordan 5 oreo...

"The great irony of this tragic spill in Arkansas is that the transport of tar sands oil through pipelines in the US is exempt from payments into the Oil Spill Liability Trust Fund. Exxon, like all companies shipping toxic tar sands, doesn't have to ...

Comment by jordans for sale

jordans for sale...

This was a bit frustrating to me on several holes where I couldn't figure out which club to hit and a couple times, I quite frankly got screwed by not knowing where bunkers were and water hazards crossed the fairway, etc. Luckily the course is in grea...

Comment by jordan 11 low concord

jordan 11 low concord...

York Times crent la peur parmi la population en affirmant, sans aucune preuve...

Comment by jordan 6 for sale

jordan 6 for sale...

Dont ask me why, but I like to think of JCreator as the body of a car, while the JDK is the engine inside the car.. For instance, a long put plus a short call is the equivalent of a synthetic short, so if no shares are available to borrow, a synthetic ...

Comment by low in frared 23 11s

low in frared 23 11s...

They're appalled by how unkindly humans treat them until they come to the home of a poor, elderly couple, Philemon and Baucis. We asked if it was possible that someone had overlooked including an X Fi or NVIDIA driver disc in our binder. The interior ...

Comment by jordan 13 for sale

jordan 13 for sale...

Legislature last week, just before he addressed a gathering of both houses....

Comment by low aqua 11s

low aqua 11s...

and CPI leader A B Bardhan as part of garnering support for Sangma, a former Lok...

Comment by infrared 23 3s

infrared 23 3s...

I also have some problems with my 3G phone in Melbourne.. Also I didn cry or ask for hugs and shit. A counselor will regularly start with asking just what issues you are going through in your relationship which made you search for relationship therapy ...

Comment by jordan 11 gamma blue

jordan 11 gamma blue...

"It is improper for someone who will one day be revered by college freshmen around the world to be seen with an unmarried woman at a Dionysian Fantasy Camp," she said.What she doesn't "get" is that there's no money in auditing, and tremendous exp...

Comment by cheap jordans online

cheap jordans online...

Don't reward their annoying behavior.. But requiring lots of parking with those units only adds to the cost for renters and worsens the traffic for everyone.. The result is that today the summit shows evidence of land forms found only in a permafrost ...

Comment by jordan 11 for sale

jordan 11 for sale...

mortgage on the company's property....

Comment by jordan shoes for sale

jordan shoes for sale...

Bishop Alfred Owens is back to his homo hating ways, Lou Chibbaro Jr. reports at DC Agenda. The pastor of Greater Mount Calvary Holy Church in Brentwood reportedly said the following to his congregation on Jan. And two women doing it don't produce no ...

Comment by buy jordans online

buy jordans online...

Gray off the hook for his 'Comcast letter' soliciting donations for the Democratic National Convention. OCF concluded that the solicitation 'was not for a campaign related activity because Gray said the money would be used to promote voting rights a...

Comment by Jordan 10 Powder Blue

Jordan 10 Powder Blue...

Sony, Christie Digital Systems, Barco and NEC are the only manufacturers permitted by the Hollywood studios to make digital cinema projectors. They must adhere to strict specifications, including anti piracy measures that can identify the exact cinema ...

Comment by jordan shoes for cheap

jordan shoes for cheap...

(:24) Largest tax cut in Iowa history: TrueThis claim relates to a 2013 rollback of commercial property taxes, which is likely the largest tax cut in Iowa history, said Jeff Robinson, a senior legislative analyst with the state's Legislative Services ...

Comment by Black Red 13s for sale

Black Red 13s for sale...

Hanover garden. And early indications suggest that the (John) Roberts Court,...

Comment by jordan 11 low aqua

jordan 11 low aqua...

in Canada.Unfortunately Cub has climbed too high and becomes stuck! All alone,...

Comment by jordan for sale

jordan for sale...

Financial educator Mary Ann Campbell has found that money attitudes such as "live within your means" are passed on through generations. Remember, this experience isn't about seeing others free of clothing, it's about setting yourself free and comin...

Comment by Carmine 6s

Carmine 6s...

The New York Times Book Review: Back Issues; Help. Some banks even offer special money skills workshops for kids, making saving money fun and understandable. "It has been a rescue mission," says Roland Horne, director of Stanford University's geothe...

Comment by cheap jordans

cheap jordans...

I don't even know how to have friends. They are now benefiting from a closer alliance with Nottingham Trent University to build a greater understanding of higher education, promote curriculum enrichment, bring their learners into contact with undergra...

Comment by bred 11s

bred 11s...

COLOMBO, Sri Lanka (AP) Pope Francis may make a 17th century priest Sri Lanka's first Roman Catholic saint during his trip next year, makingVatican confirms pope to visit Turkey in NovemberCuba sending dozens of doctors to fight EbolaTexas abortion re...

Comment by jordan 11 for sale

jordan 11 for sale...

Quincy gets to Assembly Hall on Monday on a three game, three day road trip. The...

Comment by Jordan 9 Barons

Jordan 9 Barons...

What would happen to the debate over gay marriage if an amendment to ban it were actually approved? If Massachusetts is any indication, the debate would continue. MPR's Tom Scheck spent last weekend in Boston talking to people about the issue there. M...

Comment by jordan 6 Carmine

jordan 6 Carmine...

What a terrific article. So have a look at the sad, sniveling life of a common virus, then take the necessary steps to squash it like the bug that it is.. This is a little different than the recent memorandum of understanding signed between Ford and To...

Comment by legend blue 11s

legend blue 11s...

Lenski used a simple but elegant method to find out if this would happen. He froze some of the original bacteria in each line, and then froze bacteria every 500 generations. Whenever he was so inclined, he could go back into this fossil record and thaw...

Comment by Jordan 6 Black Infrared

Jordan 6 Black Infrared...

Keogh was among the 1,400 Irishmen who travelled to Italy, and in July was appointed lieutenant in a four company battalion garrisoned in the Adriatic port city of Ancona. On September 18, the main body of the 18,000 man Papal Army was defeated in the ...

Comment by Jordan 13 Barons

Jordan 13 Barons...

We have the Kenmore Elites from 2008 not the ones w/ the steam functions though. I love them, huge capacity on the washer and even bigger for the dryer so whatever you put in the washer is going to get dry in the dryer. I agree that the towel and heavy...

Comment by the best jordan shoes

the best jordan shoes...

Really left it up to them because they in that business, and they know it better than I do, and I think it appropriate they given the support to do the work they need to do. said he is open to all the possibilities in the program, such as a mediation m...

Comment by jordan outlet

jordan outlet...

"In Volume 10, Black Jack's past takes center stage as long estranged family members suddenly decide to play an encore role in his life. Now manga's most famous doctor is not above treating festering wounds and chronic heartbreak. But in this case B...

Comment by jordan sport

jordan sport...

Socialites flock to mix and mingle. P. Diddy and J. Lo can be spotted at the Sky Bar inside the Old Shore Club. Mansion hosts the famous and the beautiful. Mynt requires a cover look, and Nikki Bar adds a new meaning to Sunday ? and it?s not football. ...

Comment by cheap jordans for sale

cheap jordans for sale...

Time it right to enjoy festivals celebrating chocolate, orchids and mangos.. Jen Hadfield's second collection, Nigh No Place ( Bloodaxe, 2008), is a celebration of the natural world from the northernmost reaches of Canada to her base in Shetland. Is o...

Comment by Jordan 13 Barons

Jordan 13 Barons...

Reformed).[2][3] Two presidents were alumni of Rutgers College the Rev....

Comment by cheap jordans

cheap jordans...

But wait! The Conservative Talking Point Mechanical Production and Dissemination Mainframe (aka Ziggy) won't be denied! Biden wasn't absolutely fucking awesome, like almost everyone at last night's Mercury sponsored viewing party thought. No, he was...

Comment by Carmine 6s

Carmine 6s...

Hand washing is the most important way of preventing spread of infection and the most important of all infection control ways. Proper hand washing removes contamination and minimises pathogens that may be transmitted either directly or indirectly to ot...

Comment by air jordan 11 gamma blue

air jordan 11 gamma blue...

Family Health Ministries will use the funds to bring HPV screening as a clinical test to Haiti for the first time, the organization said in a press release Thursday. With the approval of the Haitian Ministry of Health and Dr. One technique for examinin...

Comment by jordan 11 low concord

jordan 11 low concord...

In a government building in Jerusalem, technicians in civilian clothes sit in front of a bank of screens, trying to deflect millions of attempted attacks on Israel's government websites. A map on the wall shows sites where virtual attacks are being ca...

Comment by cheap jordans for sale

cheap jordans for sale...

FosterLockheed F 35 training work gets big boost By Richard Burnett, Orlando SentinelYears after 9 11, war kids can bury parents loss Darryl E. OwensLibraries really are reinventing themselves Beth Kassab, Local News ColumnistOrlando man arrested, accu...

Comment by order Barons 13s

order Barons 13s...

According to foreign researchers, the country had 20 ankang institutions (high security psychiatric hospitals for the criminally insane) directly administered by the Ministry of Public Security (MPS). Political activists, underground religious believer...

Comment by sport blue 6s

sport blue 6s...

In 1986, after Libya was linked to the bombing of a disco in Germany that killed two American soldiers, President ordered air strikes on the country. There are of course more option. He says. Though as with the waterblock situation, you might be better...

Comment by Jordan 13 Barons

Jordan 13 Barons...

Occupy San Francisco plans to down all modes of transportation from Marin to San Francisco, as reported by CNS News. The May Day Flier from the Golden Gate Labor Coalition calls for a protest next to the bridge that insists the Bridge District also: re...

Comment by authentic jordans

authentic jordans...

"Flirting has a lot to do with a person's attitude," he explains. "Don't be afraid to take risks and don't worry about being rejected. Smile at people, specially at the ones you flirt with. The statutes are full of references to marriage as being...

Comment by jordan 6 sprot blue

jordan 6 sprot blue...

En octobre 2001, le Prsident a organis un forum pour la rconciliation nationale, afin d'examiner les problmes qui divisaient le peuple ivoirien, notamment les questions relatives la nationalit, la proprit de la terre, la lgitimit conteste de son gouve...

Comment by jordan 11 legend blue

jordan 11 legend blue...

In 2004, voters in 11 states passed ballot initiatives banning same sex marriages. And yet in the last election, pro marriage equality candidates like Connecticut state Sen. Andrew J. McDonald, D Stamford, were returned to office by voters. McDonald is...

Comment by jordan 11 low concord

jordan 11 low concord...

A public hearing will be held on the rules this summer.But Taylor said the rules don't meet the standard of an "emergency.""There's no threat to the public health and safety of people coming to sing a song over the noon hour," she said, referring...

Comment by jordan 13 black red

jordan 13 black red...

If you are a small business owner you might think your company is an unlikely target for a cyber attack. After all, who'd bother attacking a little firm like yours when they can go after a big bank or insurance company? You may be more vulnerable than...

Comment by Jordan 13 Black Red

Jordan 13 Black Red...

They just pack her stuff and say bye. Actually, only when something happens do I hear anything from them. But, if I ask, "so how was her day", then I get more specific responses.. My comments today are outlined on Slide Four. This quarter I'll talk ...

Comment by jordans for cheap

jordans for cheap...

Today, with a new set of warnings flashing before us, and a wide range of new challenges to our security and our safety, we again face a choice. Act now, and put in place safeguards to protect this country and our people. Or act later, when it is too l...

Comment by jordan 13 hologram

jordan 13 hologram...

Studies have shown that it's difficult for hospitals to get a vaccination coverage rate of over 70 per cent for staff on a voluntary basis. Coverage at Virginia Mason Hospital in Oregon jumped to 97.6 per cent in 2005 after vaccination was made a cond...

Comment by Black Infrared 6s

Black Infrared 6s...

The imminent arrival of the H1N1 swine flu vaccine is welcome news, because the flu which continues to produce mild illness and fairly quick recovery in most people continues to spread around the country. That unusual because the typical seasonal ( flu...

Comment by Max Edwards

Just a quick note to say that using Mongo 2.4 I can use the aggregation framework with binary guids.

Max Edwards
Comment by Vishnu Viswanath

Hi Mikael,

So can you suggest any alternative to the ToDynamic function?

Regards

Vishnu Viswanath
Comment by Magnus Gudmundsson

Thanks for the article Mikael, it has been really helpful. I am struggling trying to do something similar to the aggregation described here : stackoverflow.com/.../15940554#15940554

question: how would you express the arrays found in projection2 ?

"$subtract" : [
"$saleDate",
{
"$add" : [
"$ml",
{
"$multiply" : [
"$s",
1000
]
},
(etc etc)

Im guessing these would be arrays of BsonDocuments, but my head is hurting trying to describe these in C#. Can you help me out? Please ??? :)

Comment by Mehul

It has problems with _id field also, any other alternative ?

Mehul
Comment by gerhard grossberger

Hi Mikael, great article - thanks!
I managed to do the aggregation this way, but I would also like to use $distinct. I couldn´t get this to work straight ahead. I got an "Unrecognized pipeline stage name: '$distinct' " Any Ideas?

gerhard grossberger
Comment by gerhard grossberger

Figured it out, distinct doesn´t work in AggregationPipeline. I now switched to using $group.

gerhard grossberger
Comment by jordans for sale

jordans for sale...

(AP Photo/Michael Dwyer)Industry growing around marijuana ediblesMelissa Fitzgerald discusses how to prepare a cannabis infused dipping sauce at the New England Grass Roots Institute in Quincy, Mass., on July 10, 2014. Fighters from Chad, Cameroon and ...

Comment by låna 10000

låna 10000...

Letar du efter en Co hypotekslan uppskattning pa allvar är inte väldigt annorlunda än att försöka hitta hypotekslan pa annan plats innanför Oughout...

Comment by företagslån utan säkerhet

företagslån utan säkerhet...

De kunde användas för att betala tillbaka finansiella ataganden , hem konstruktion , sjukhusräkningar, bilreparationer , eller ikapp pa saker du är skyldiga att betala tillbaka...