Skip to content

MongoDB Aggregate

Rafael J. Rodriguez edited this page Jan 6, 2017 · 2 revisions

Author

@Rafase282

Created by Rafase282

Github | FreeCodeCamp | CodePen | LinkedIn | Medium Website | E-Mail

MongoDB Aggregate

Next up is aggregation. Aggregation allows one to do things like calculate the sum of a field of multiple documents or the average of a field of documents meeting particular criteria.

Say you have a collection named prices. Each price document is modeled like so:

{
  "name": "Tshirt",
  "size": "S",
  "price": 10,
  "quantity": 12
  "meta": {
    "vendor": "hanes",
    "location": "US"
  }
}

In this exercise, we need to calculate the average price for all documents in prices that have the size that will be passed as the first argument to your script.

Use console.log() to print the average price rounded to 2 decimal places to stdout after you have found it.

HINTS

To use the aggregate() function, one first needs the collection. The aggregate() function takes an array of objects as the first argument.

This array will contain the different pipelines for the aggregation. To read more about pipelines, please visit Aggregation.

The two main pipeline stages we will use will be $match and $group.

$match

$match is used similar to the way a query is done. It allows us to select the documents that meet certain criteria.

Ex.

var match = { $match: { status: 'A' } }

The above example will match all of the documents that have a status property equal to A.

$group

$group is what allows us to run operations on certain properties.

So, say we wanted to get the sum of the values of the property value where status is equal to A and have it placed in the total property.

Ex.

// [
//  { status: 'A', value: 1 },
//  { status: 'B', value: 2 },
//  { status: 'A', value: 10 }
// ]

collection.aggregate([
  { $match: { status: 'A' }}
, { $group: {
    _id: 'total' // This can be an arbitrary string in this case
  , total: {
      // $sum is the operator used here
      $sum: '$value'
    }
  }}
]).toArray(function(err, results) {
  // handle error
  console.log(results)
  // => [
  // =>   { _id: 'total', total: 11 }
  // => ]
})

Other operators used in the $group stage include:

  • $avg
  • $first
  • $last
  • $max
  • $min
  • $push
  • $addToSet

Getting Started

  1. Welcome!
  2. Contact
  3. Get Started with Free Code Camp

Front End Development Certification

  1. HTML5 and CSS
  2. Responsive Design with Bootstrap
  3. Gear up for Success
  4. jQuery
  5. Basic JavaScript
  6. Object Oriented and Functional Programming
  7. Basic Algorithm Scripting
  8. Basic Front End Development Projects
  9. Intermediate Algorithm Scripting
  10. JSON APIs and Ajax
  11. Intermediate Front End Development Projects
  12. Claim Your Front End Development Certificate

Data Visualization Certification

  1. SASS
  2. React
  3. React Projects
  4. D3
  5. Data Visualization Projects
  6. Claim Your Data Visualization Certificate

Back End Development Certification

  1. Upper Intermediate Algorithm Scripting
  2. Automated Testing and Debugging
  3. Advanced Algorithm Scripting
  4. AngularJS (Legacy Material)
  5. Git
  6. Node.js and Express.js
  7. MongoDB
  8. API Projects
  9. Dynamic Web Applications
  10. Claim Your Back End Development Certificate

Full Stack Development Certification

  1. Greefield Nonprofit Project 1
  2. Greefield Nonprofit Project 2
  3. Legacy Nonprofit Project 1
  4. Legacy Nonprofit Project 2
  5. Claim your Full Stack Development Certification

Coding Interview Preparation

  1. Whiteboard Coding Interview Training
  2. Critical Thinking Interview Training
  3. Mock Interview 1
  4. Mock Interview 2
  5. Mock Interview 3
Clone this wiki locally