Aggregation Pipeline Operators

The aggregation pipeline operators construct expressions for use in the aggregation pipeline stages. The following are the list of Aggregation Pipeline Operators.

Arithmetic Expression Operators

It is used to perform arithmetic operations on numbers. Some arithmetic expression also supports data arithmetic.

$abs

The abs operator returns the absolute value of a number.

Syntax:

snippet
{ $abs: <number> }

Example:

snippet
db.score.aggregate([
   {
     $school: { marks: { $abs: { $subtract: [ "$max", "$min" ] } } }
   }
])

$add

It adds two or more numbers and a date. If one of the arguments is a date, then the date treats the other argument as milliseconds to add to the date.

Syntax:

snippet
{ $add: [ <expression1>, <expression2>, ... ] }

Example:

snippet
db.books.aggregate(
   [
     { $project: { item: 1, total: { $add: [ "$price", "$tax" ] } } }
   ]
)

$ceil

The ceil operator returns the smallest integer that is greater than or equal to the specified number.

Syntax:

snippet
{ $ceil: <number> }

Example:

snippet
db.samples.aggregate([ { $project: { value: 1, ceilingValue: { $ceil: "$value" } } } ])

$divide

It divides one or more numbers by another and returns the result.

Syntax:

snippet
{ $divide: [ <expression1>, <expression2> ] }

Example:

snippet
db.planning.aggregate( [ { $project: { name: 1, workdays: { $divide: [ "$hours", 8 ] } } } ] )

$exp

The exp operator is used to raise Euler's number to the specified exponent and returns the result.

Syntax:

snippet
{ $exp: <exponent> }

Example:

snippet
db.accounts.aggregate( [ { $project: { effectiveRate: { $subtract: [ { $exp: "$rate"}, 1 ] } } } ] )

$floor

The floor operator returns the greatest integer less than or equal to the specified number.

Syntax:

snippet
{ $floor: <number> }

Example:

snippet
db.samples.aggregate( [ { $project: { value: 1, floorValue: { $floor: "$value" } } } ] )

$ln

The ln operator calculates the natural logarithm of a number and returns the result as a double.

Syntax:

snippet
{ $ln: <number> }

Example:

snippet
db.sales.aggregate( [ { $project: { x: "$year", y: { $ln: "$sales"  } } } ] )

$log

The log operator calculates the log of a number for the specified base and returns the result as double.

Syntax:

snippet
{ $log: [ <number>, <base> ] }

Example:

snippet
db.examples.aggregate([
   { $project: { bitsNeeded:
      {
         $floor: { $add: [ 1, { $log: [ "$positiveInt", 2 ] } ] } } }
      }
])

$log10

The log10 operator calculates the log base 10 of a number and returns the result as a double.

Syntax:

snippet
{ $log10: <number> }

Example:

snippet
db.samples.aggregate( [ { $project: { pH: { $multiply: [ -1, { $log10: "$H3O" } ] } } } ] )

$mod

The mod operator divides one number with another and returns the remainder.

Syntax:

snippet
{ $mod: [ <expression1>, <expression2> ] }

Example:

snippet
db.planning.aggregate(
   [
     { $project: { remainder: { $mod: [ "$hours", "$tasks" ] } } }
   ]
)

$multiply

The multiply operator gives the product of two or more numbers.

Syntax:

snippet
{ $multiply: [ <expression1>, <expression2>, ..... ] }

Example:

snippet
db.sales.aggregate( [ { $project: { date: 1, item: 1, total: { $multiply: [ "$price", "$quantity" ] } } } ] )

$pow

The pow operator raises the number to the given exponent and returns the result.

Syntax:

snippet
{ $pow: [ <number>, <exponent> ] }

Example:

snippet
db.quizzes.aggregate( [ { $project: { variance: { $pow: [ { $stdDevPop: "$scores.score" }, 2 ] } } } ] )

$round

The round operator rounds a number to a whole integer or a specified decimal place.

Syntax:

snippet
{ $round : [ <number>, <place> ] }

Example:

snippet
db.samples.aggregate( [ { $project: { roundedValue: { $round: [ "$value", 1 ] } } } ] )

$sqrt

The sqrt operator returns the square root of a positive number as double.

Syntax:

snippet
{ $sqrt: <number> }

Example:

snippet
db.points.aggregate([
   {
     $project: {
        distance: {
           $sqrt: {
               $add: [
                  { $pow: [ { $subtract: [ "$p2.y", "$p1.y" ] }, 2 ] },
                  { $pow: [ { $subtract: [ "$p2.x", "$p1.x" ] }, 2 ] }
               ]
           }
        }
     }
   }
])

$subtract

The subtract operator subtracts two or more numbers to return the difference of the number.

Syntax:

snippet
{ $subtract: [ <expression1>, <expression2> ] }

Example:

snippet
db.sales.aggregate( [ { $project: { item: 1, total: { $subtract: [ { $add: [ "$price", "$fee" ] }, "$discount" ] } } } ] )

$trunc

The trunc command deletes the data from the specified decimal place.

Syntax:

snippet
{ $trunc : [ <number>, <place> ] }

Example:

snippet
db.samples.aggregate( [ { $project: { truncatedValue: { $trunc: [ "$value", 1 ] } } } ] )

Array Expression Operator

$arrayElemAt

It returns the element at the specified array index.

Syntax:

snippet
{ $arrayElemAt: [ <array>, <idx> ] }

Example:

snippet
db.users.aggregate([
   {
     $project:
      {
         name: 1,
         first: { $arrayElemAt: [ "$favorites", 0 ] },
         last: { $arrayElemAt: [ "$favorites", -1 ] }
      }
   }
])

$arrayToObject

The arrayToObject operator converts an array into a single document.

Syntax:

snippet
[ [ "item", "abc123"], [ "qty", 25 ] ]

Example:

snippet
db.inventory.aggregate(
   [
      {
         $project: {
            item: 1,
            dimensions: { $arrayToObject: "$dimensions" }
         }
      }
   ]
)

$concatArrays

The concatArrays operator joins the array to return the concatenated array.

Syntax:

snippet
{ $concatArrays: [ <array1>, <array2>, ... ] }

Example:

snippet
db.warehouses.aggregate([
   { $project: { items: { $concatArrays: [ "$instock", "$ordered" ] } } }
])

$filter

The filter operator selects a subset of an array to return the result based on the specified condition.

Syntax:

snippet
{ $filter: { input: <array>, as: <string>, cond: <expression> } }

Example:

snippet
db.sales.aggregate([
   {
      $project: {
         items: {
            $filter: {
               input: "$items",
               as: "item",
               cond: { $gte: [ "$$item.price", 100 ] }
            }
         }
      }
   }
])

$in

The in operator returns a boolean indicating that the specified value is in the array or not.

Syntax:

snippet
{ $in: [ <expression>, <array expression> ] }

Example:

snippet
db.fruit.aggregate([
  {
    $project: {
      "store location" : "$location",
      "has bananas" : {
        $in: [ "bananas", "$in_stock" ]
      }
    }
  }
])

$indexOfArray

The indexOfArray operator searches the array for the occurrence of a specified value and returns the array index of the first occurrence.

Syntax:

snippet
{ $indexOfArray: [ <array expression>, <search expression>, <start>, <end> ] }

Example:

snippet
db.inventory.aggregate(
   [
     {
       $project:
          {
            index: { $indexOfArray: [ "$items", 2 ] },
          }
      }
   ]
)

$isArray

It determines and returns a Boolean value if the operand is an Array.

Syntax:

snippet
{ $isArray: [ <expression> ] }

Example:

snippet
db.shop.aggregate( [ { $project: { items: { $cond:
            { if: { $and: [ { $isArray: "$instock" }, { $isArray: "$ordered" } ] }, then: { $concatArrays: [ "$instock", "$ordered" ] },
        else: "One or more fields is not an array." } } } } )

$map

The map operator attaches value to each item in an array and returns an array with the applied result.

Syntax:

snippet
{ $map: { input: <expression>, as: <string>, in: <expression> } }

Example:

snippet
db.grades.aggregate(
   [
      { $project:
         { adjustedGrades:
            {
              $map:
                 {
                   input: "$quizzes",
                   as: "grade",
                   in: { $add: [ "$$grade", 2 ] }
                 }
            }
         }
      }
   ]
}

$objectToArray

This operator converts a document to an array.

Syntax:

snippet
{ $objectToArray: <object> }

Example:

snippet
db.inventory.aggregate(
   [
      {
         $project: {
            item: 1,
            dimensions: { $objectToArray: "$dimensions" }
         }
      }
   ]
)

$range

The range operator returns an array whose elements are a generated sequence of numbers.

Syntax:

snippet
{ $range: [ <start>, <end>, <non-zero step> ] }

Example:

snippet
db.distances.aggregate([{
    $project: {
        _id: 0,
        city: 1,
        "Rest stops": { $range: [ 0, "$distance", 25 ] } } } ] )

$reduce

The reduce operator applies an expression to each element in an array and combines them into a single value.

Syntax:

snippet
{
    $reduce: {
        input: <array>,
        initialValue: <expression>,
        in: <expression>
    }
}

Example:

snippet
db.clothes.aggregate( [ { $project: { "discountedPrice": {
          $reduce: { input: "$discounts", initialValue: "$price", in: { $multiply: [ "$$value", { $subtract: [ 1, "$$this" ] } ] } } } } } ] )

$reverseArray

It returns an array with the element in reverse order.

Syntax:

snippet
{ $reverseArray: <array expression> }

Example:

snippet
db.users.aggregate( [ { $project: {name: 1,
reverseFavorites: { $reverseArray: "$favorites" } } } ] )

$size

The size operator counts and returns the total number of items in an array.

Syntax:

snippet
{ $size: <expression> }

Example:

snippet
db.books.aggregate( [ { $project: { item: 1, numberOfColors: { $cond: { if: { $isArray: "$colors" }, then: { $size: "$colors" }, else: "NA"} } } } ] )

$slice

The slice operator results in a subset of an array.

Syntax:

snippet
{ $slice: [ <array>, <n> ] }

Example:

snippet
db.books.aggregate( [ { $project: { name: 1, threeFavorites: { $slice: [ "$favorites", 3 ] } } }
])

$zip

The zip operator transposes an array so that the first element of the output array would be an array containing the first element of the first input array.

Syntax:

snippet
{
    $zip: { inputs: [ <array expression1>,  ... ], useLongestLength: <boolean>, defaults:  <array expression> } }

Example:

snippet
db.matrices.aggregate([{ $project: {  _id: false,   transposed: { $zip: { inputs: [
          { $arrayElemAt: [ "$matrix", 0 ] },
          { $arrayElemAt: [ "$matrix", 1 ] },
          { $arrayElemAt: [ "$matrix", 2 ] },
        ] } } } } ] )
Related Tutorial
Follow Us
https://www.facebook.com/Rookie-Nerd-638990322793530 https://twitter.com/RookieNerdTutor https://plus.google.com/b/117136517396468545840 #
Contents +