Skip to content

Instantly share code, notes, and snippets.

@danielstreit
Last active August 29, 2015 14:05
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save danielstreit/ea429033dc18c06cab7a to your computer and use it in GitHub Desktop.
Save danielstreit/ea429033dc18c06cab7a to your computer and use it in GitHub Desktop.
A primer on MongoDB Aggregation Pipeline
// In the MongoDB Aggregation Pipeline, each stage is represented by an object.
// The type of stage must be one MongoDB's predefined stage types. There are
// a variety of stage types, but some of the most useful are: $match, $group,
// $project, and $sort. See the MongoDB manual for an exhaustive list.
// Lets look at some examples to see how each works. Then, we'll put them
// together in the pipeline.
// Lets say we have a database of kittens with various information about each.
// A match stage might look like this:
{ $match: { breed: 'ocelot' } };
// This collects all the cats whose breed is ocelot.
// $match behaves much like find(). What if we wanted all kittens born within
// the last year?
{ $match: { birthdate: { $gt: aDate } } };
// This will collect all of the cats born on a date greater than the value
// associated with the $gt key. Notice how the $gt operator is used. It must
// be in its own object. In order to be a valid aggregation stage, it
// must be valid JSON.
// $group does what its name implies, it groups documents together.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment