Arithmetic operator

abs

Returns the absolute value of a number.

API
db.command.aggregate.abs(<number>)
Copy the code

The value passed by ABS, in addition to numeric constants, can also be any expression that ultimately resolves to a number.

If the expression resolves to NULL or points to a nonexistent field, the abs result is NULL. If the value resolves to NaN, the result is NaN.

The sample

Collection ratings have the following records:

{ _id: 1, start: 5, end: 8 }
Copy the code

Obtain the absolute difference between start and end of each record:

const $ = db.command.aggregate
db.collection('ratings').aggregate()
  .project({
    delta: $.abs($.subtract(['$start'.'$end'))}).end(a)Copy the code

Results:

{ _id : 1, delta : 3 }
Copy the code

add

Add numbers or add them to dates. If one of the values in the array is a date, the other values are treated as milliseconds added to that date.

API
db.command.aggregate.add([<expression1>.<expression2>. ] )Copy the code

The expression can be a specified field of the form $+ that can be parsed to a string.

The sample

The set staff has the following records:

{ _id: 1, department: "x", sales: 5, engineer: 10, lastUpdate: ISODate("2019-05-01T00:00:00Z") }
{ _id: 2, department: "y", sales: 10, engineer: 20, lastUpdate: ISODate("2019-05-01T02:00:00Z")}Copy the code

Digital sum

Obtain the total number of each record:

const $ = db.command.aggregate
db.collection('staff').aggregate()
  .project({
    department: 1,
    total: $.add(['$sales'.'$engineer'])}).end(a)Copy the code

Results:

{ _id: 1, department: "x", total: 15 }
{ _id: 2, department: "y", total: 30 }
Copy the code

Add date value

Get the value of each record’s lastUpdate plus one hour:

const $ = db.command.aggregate
db.collection('staff').aggregate()
  .project({
    department: 1,
    lastUpdate: $.add(['$lastUpdate'.60*60*1000])}).end(a)Copy the code

Results:

{ _id: 1, department: "x", lastUpdate: ISODate("2019-05-01T01:00:00Z") }
{ _id: 2, department: "y", lastUpdate: ISODate("2019-05-01T03:00:00Z")}Copy the code

ceil

Rounding up returns the smallest integer greater than or equal to the given number.

API
db.command.aggregate.ceil(<number>)
Copy the code


can be any expression that resolves to a number. Returns NULL if the expression resolves to NULL or points to a non-existent field, or NaN if the expression resolves to NaN.

The sample

Set SALES has the following records:

{ _id: 1, sales: 5.2 }
{ _id: 2, sales: 3.2 }
Copy the code

Take the upward round of each number:

const $ = db.command.aggregate
db.collection('sales').aggregate()
  .project({
    sales: $.ceil('$sales')}).end(a)Copy the code

Results:

{ _id: 1, sales: 6 }
{ _id: 2, sales: - 3 }
Copy the code

divide

Pass in the dividend and divisor and find the quotient.

API
db.command.aggregate.divide([<Dividend expression>.<Divisor expression>])
Copy the code

An expression can be any expression that resolves to a number.

The sample

Railroads are as follows:

{ _id: 1, meters: 5300 }
{ _id: 3, meters: 130 }
Copy the code

Take the value of each number converted into kilometers:

const $ = db.command.aggregate
db.collection('railroads').aggregate()
  .project({
    km: $.divide(['$meters'.1000])}).end(a)Copy the code

Results:

{ _id: 1, km: 5.3 }
{ _id: 3, km: 0.13 }
Copy the code

exp

Take e to the NTH power.

API
db.command.aggregate.exp(<exponent>)
Copy the code


can be any expression that resolves to a number. Returns NULL if the expression resolves to NULL or points to a non-existent field, or NaN if the expression resolves to NaN.

The sample

The set Math has the following records:

{ _id: 1, exp: 0 }
{ _id: 2, exp: 1 }
Copy the code
const $ = db.command.aggregate
db.collection('math').aggregate()
  .project({
    result: $.exp('$exp')
  })
  .end()
Copy the code

Results:

{ _id: 1, result: 1 }
{ _id: 2, result: 2.71828182845905 }
Copy the code

floor

Round down to return the smallest integer greater than or equal to the given number.

API
db.command.aggregate.floor(<number>)
Copy the code


can be any expression that resolves to a number. Returns NULL if the expression resolves to NULL or points to a non-existent field, or NaN if the expression resolves to NaN.

The sample

Set SALES has the following records:

{ _id: 1, sales: 5.2 }
{ _id: 3, sales: 3.2 }
Copy the code

Take the downward round of each number:

const $ = db.command.aggregate
db.collection('sales').aggregate()
  .project({
    sales: $.floor('$sales')}).end(a)Copy the code

Results:

{ _id: 1, sales: 5 }
{ _id: 3, sales: - 6 }
Copy the code

ln

Computes the given number in the natural log.

API
db.command.aggregate.ln(<number>)
Copy the code


can be any expression that resolves to a non-negative number.

Ln is equivalent to log([

, math.e]), where math.e is the JavaScript method for obtaining the value of E.

The sample

Computes the given number in the natural log.

db.command.aggregate.ln(<number>)
Copy the code


can be any expression that resolves to a non-negative number.

Ln is equivalent to log([

, math.e]), where math.e is the JavaScript method for obtaining the value of E.

log

Computes the log of a given number at the base of a given logarithm.

API
db.command.aggregate.log([<number>.<base>])
Copy the code


can be any expression that resolves to a non-negative number.
can be any expression that resolves to a number greater than 1.

Log returns NULL if any of the arguments resolves to NULL or points to a nonexistent field. If any of the arguments resolves to NaN, log returns NaN.

The sample

The set curve has the following records:

{ _id: 1, x: 1 }
{ _id: 2, x: 2 }
Copy the code

Calculate the value of log2(x) :

const $ = db.command.aggregate
db.collection('staff').aggregate()
  .project({
    log: $.log(['$x'.2])}).end(a)Copy the code

Results:

{ _id: 1, log: 0 }
{ _id: 2, log: 1 }
Copy the code

log10

Compute the log of a given number at log base 10.

API
db.command.aggregate.log(<number>)
Copy the code


can be any expression that resolves to a non-negative number.

Log10 is equivalent to the second argument to the log method, which is fixed at 10.

mod

Modulo operation, take the value of the number modulo.

API
db.command.aggregate.mod([<dividend>.<divisor>])
Copy the code

The first number is the dividend and the second number is the divisor. The argument is any expression that resolves to a number.

The sample

Set shopping has the following records:

{ _id: 1, bags: 3, items: 5 }
{ _id: 2, bags: 2, items: 8 }
Copy the code

Take the remainder of items divided by bags for each record (items % bags) :

const $ = db.command.aggregate
db.collection('shopping').aggregate()
  .project({
    overflow: $.mod(['$items'.'$bags'])}).end(a)Copy the code

Results:

{ _id: 1, log: 2 }
{ _id: 2, log: 0 }
Copy the code

multiply

Takes the result of multiplying the numeric arguments passed in.

API
db.command.aggregate.multiply([<expression1>.<expression2>. ] )Copy the code

The argument is any expression that resolves to a number.

The sample

Collection FRUITS has the following records:

{ "_id": 2."price": 15."quantity": 50 }
Copy the code

Find the total price of each fruit:

const $ = db.command.aggregate
db.collection('fruits').aggregate()
  .project({
    name: 1,
    total: $.multiply(['$price'.'$quantity']),}).end(a)Copy the code

Results:

{ "_id": 2."name": "orange"."total": 750 }
Copy the code

pow

Find the exponential power of a given radix.

API
db.command.aggregate.pow([<base>.<exponent>])
Copy the code

The argument is any expression that resolves to a number.

The sample

Collection STATS has the following records:

{ "_id": 1."x": 2."y": 3 }
{ "_id": 2."x": 5."y": 7 }
Copy the code

Find the sum of the squares of x and y:

const $ = db.command.aggregate
db.collection('stats').aggregate()
  .project({
    sumOfSquares: $.add([$.pow(['$x'.2]), $.pow(['$y'.2]]),}).end(a)Copy the code

Results:

{ "_id": 1."sumOfSquares": 13 }
{ "_id": 2."sumOfSquares": 74 }
Copy the code

sqrt

Take the square root.

API
db.command.aggregate.sqrt([<number>])
Copy the code

The argument is any expression that resolves to a non-negative number.

The sample

The right triangle set Triangle has the following records:

{ "_id": 1."x": 2."y": 3 }
{ "_id": 2."x": 5."y": 7 }
{ "_id": 3."x": 10."y": 20 }
Copy the code

X and y are two right-angled sides respectively, then find the hypotenuse length:

const $ = db.command.aggregate
db.collection('triangle').aggregate()
  .project({
    len: $.sqrt([$.add([$.pow(['$x'.2]), $.pow(['$y'.2]])]),}).end(a)Copy the code

Results:

{ "_id": 1."len": 3.605551275463989 }
{ "_id": 2."len": 8.602325267042627 }
{ "_id": 3."len": 22.360679774997898 }
Copy the code

subtract

Subtract two numbers and return the difference, or subtract two dates and return the number of milliseconds, or subtract a number from a date and return the date of the result.

API
db.command.aggregate.subtract([<expression1>.<expression2>])
Copy the code

Arguments are any expression that resolves to a number or date.

The sample

Set scores has the following records:

{ "_id": 1."max": 10."min": 1 }
{ "_id": 2."max": 7."min": 5 }
Copy the code

Find the difference between Max and min of each record. :

const $ = db.command.aggregate
db.collection('scores').aggregate()
  .project({
    diff: $.subtract(['$max'.'$min'])}).end(a)Copy the code

Results:

{ "_id": 1."diff": 9 }
{ "_id": 2."diff": 2 }
Copy the code

trunc

Truncate the number to an integer.

API
db.command.aggregate.trunc(<number>)
Copy the code

The argument is any expression that resolves to a number.

The sample

Set scores has the following records:

{ "_id": 1."value": 1.21 }
Copy the code
const $ = db.command.aggregate
db.collection('scores').aggregate()
  .project({
    int: $.trunc('$value')}).end(a)Copy the code

Results:

{ "_id": 1."value": 1 }
Copy the code

Array operator

arrayElemAt

Returns the element at the specified array subscript.

API
db.command.aggregate.arrayElemAt([<array>.<index>])
Copy the code


can be any expression that resolves to a number.


can be any expression that resolves to an integer. ArrayElemAt returns the element at index if it is positive, or the element at index from the end of the array if it is negative.

The sample

Collection EXAMS have the following records:

{ "_id": 1."scores": [80.60.65.90]} {"_id": 2."scores": [78]}Copy the code

Find the scores of each first test and the scores of the last test:

const $ = db.command.aggregate
db.collection('exams').aggregate()
  .project({
    first: $.arraElemAt(['$scores'.0]),
    last: $.arraElemAt(['$scores'.- 1]),}).end(a)Copy the code

Results:

{ "_id": 1."first": 80."last": 90 }
{ "_id": 2."first": 78."last": 78 }
Copy the code

arrayToObject

Convert an array to an object.

API

There are two types of syntax:

The first way is to pass in a two-dimensional array. The length of the second two-dimensional array must be 2. The first value is the field name and the second value is the field value

db.command.aggregate.arrayToObject([
  [<key1>.<value1>],
  [<key2>.<value2>],
  ...
])
Copy the code

The second way is to pass in an array of objects that must contain fields K and v, specifying the field name and value, respectively

db.command.aggregate.arrayToObject([
  { "k": <key1>, "v": <value1> },
  { "k": <key2>, "v": <value2> },
  ...
])
Copy the code

The parameters passed to arrayToObject are fine as long as they can be parsed into one of the two representations above.

The sample

Aggregate shops are recorded as follows:

{ "_id": 1."sales": [["max".100], ["min".50]]} {"_id": 3."sales": [{"k": "max"."v": 50 }, { "k": "min"."v": 30}}]Copy the code

Calculate the scores of each first and last exam:

const $ = db.command.aggregate
db.collection('shops').aggregate()
  .project({
    sales: $.arrayToObject('$sales'),}).end(a)Copy the code

Returns:

{ "_id": 1."sales": { "max": 100."min": 50}} {"_id": 3."sales": { "max": 50."min": 30}}Copy the code

concatArrays

Concatenate multiple arrays into one array.

API
db.command.aggregate.arrayToObject([ <array1>.<array2>. ] )Copy the code

The argument is any expression that resolves to an array.

The sample

The collection items have the following records:

{ "_id": 1."fruits": [ "apple"]."vegetables": [ "carrot"]}Copy the code
const $ = db.command.aggregate
db.collection('items').aggregate()
  .project({
    list: $.concatArrays(['$fruits'.'$vegetables']),}).end(a)Copy the code

Results:

{ "_id": 1."list": [ "apple"."carrot"]}Copy the code

filter

Returns a subset of arrays that satisfy a given condition.

API
db.command.aggregate.filter({  input: <array>.as: <string>,  cond: <expression>})
Copy the code
field instructions
input An expression that can be parsed into an array
as Optional variable that represents the elements of the array. Default is this
cond An expression that can be parsed as a Boolean value to determine whether or not each element satisfies the condition. Each element’s name is determined by the as argument
The prefix, such as The prefix, such as
This)

The argument is any expression that resolves to an array.

The sample

Collection FRUITS has the following records:

{
  "_id": 1."stock": [{"name": "apple"."price": 10 },
    { "name": "orange"."price": 20}}],Copy the code
const _ = db.command
const $ = db.command.aggregate
db.collection('fruits').aggregate()
  .project({
    stock: $.filter({
      input: '$stock'.as: 'item',
      cond: $.gte(['$$item.price'.15])})}).end(a)Copy the code

Results:

{ "_id": 1."stock": [{"name": "orange"."price": 20}}]Copy the code

in

Given a value and an array, return true if the value is in the array, false otherwise.

API
db.command.aggregate.in([<value>.<array>])
Copy the code


can be any expression.


can be any expression that resolves to an array.

The sample

Aggregate shops are recorded as follows:

{ "_id": 1."topsellers": ["bread"."ice cream"."butter"]} {"_id": 2."topsellers": ["ice cream"."cheese"."yagurt"]}Copy the code

Mark the highest selling item contains the ice Cream record.

const $ = db.command.aggregate
db.collection('price').aggregate()
  .project({
    included: $.in(['ice cream'.'$topsellers'])}).end(a)Copy the code

Results:

{ "_id": 1."included": true }
{ "_id": 2."included": true }
Copy the code

indexOfArray

Finds the index of the first element in the array equal to the given value, or returns -1 if none is found.

API
db.command.aggregate.indexOfArray([ <array expression>.<search expression>.<start>.<end> ])
Copy the code
field type instructions
string An expression that can be parsed to an array. If parsed to NULL, indexOfArray returns NULL
string Conditional matching expressions applied to individual elements of data
integer Optional, used to specify the start index of the search, which must be a non-negative integer
integer This parameter is optional. The end index used to specify the search must be a non-negative integer

The argument is any expression that resolves to an array.

The sample

Collection STATS has the following records:

{
  "_id": 1."sales": [ 1.6.2.2.5]} {"_id": 2."sales": [ 4.2.1.5.2]}Copy the code
const $ = db.command.aggregate
db.collection('stats').aggregate()
  .project({
    index: $.indexOfArray(['$sales'.2.2])}).end(a)Copy the code

Results:

{ "_id": 1."index": 2 }
{ "_id": 2."index": 4 }
Copy the code

isArray

Checks whether the given expression is an array and returns a Boolean value.

API
db.command.aggregate.isArray(<expression>)
Copy the code

Arguments are arbitrary expressions.

The sample

Collection STATS has the following records:

{
  "_id": 1."sales": [ 1.32.6.93.2.48.2.82.5.74]} {"_id": 2."sales": [ 2.97.7.13.1.58.6.37.3.69]}Copy the code

Calculate the total sales volume by finding sales * base if sales is a number, or multiplying the sum of array elements with base if sales is an array.

const $ = db.command.aggregate
db.collection('stats').aggregate()
  .project({
    truncated: $.map({
      input: '$sales'.as: 'num'.in: $.trunc('$$num'),
    })
  })
  .project({
    total: $.sum('$truncated')}).end(a)Copy the code

Results:

{ "_id": 1."index": 16 }
{ "_id": 2."index": 19 }
Copy the code

map

Similar to the map method on Array.

API
db.command.aggregate.map({
  input: <expression>.as: <string>.in: <expression>
})
Copy the code
field instructions
input An expression that can be parsed into an array
as Optional variable that represents the elements of the array. Default is this
in An expression that can be applied to the elements of a given array whose names are determined by the AS argument
The prefix, such as The prefix, such as
This)
The sample

Collection STATS has the following records:

{
  "_id": 1."sales": [ 1.32.6.93.2.48.2.82.5.74]} {"_id": 2."sales": [ 2.97.7.13.1.58.6.37.3.69]}Copy the code

Truncate the numbers into integers and sum them

const $ = db.command.aggregate
db.collection('stats').aggregate()
  .project({
    truncated: $.map({
      input: '$sales'.as: 'num'.in: $.trunc('$$num'),
    })
  })
  .project({
    total: $.sum('$truncated')}).end(a)Copy the code

Results:

{ "_id": 1."index": 16 }
{ "_id": 2."index": 19 }
Copy the code

objectToArray

Convert an object to an array. Method turns each key-value pair of the object into an element of the output array of the form {k:

, v:

}.

API
db.command.aggregate.objectToArray(<object>)
Copy the code
The sample

The collection items have the following records:

{ "_id": 1."attributes": { "color": "red"."price": 150}} {"_id": 2."attributes": { "color": "blue"."price": 50}}Copy the code
const $ = db.command.aggregate
db.collection('items').aggregate()
  .project({
    array: $.objectToArray('$attributes')}).end(a)Copy the code

Results:

{ "_id": 1."array": [{ "k": "color"."v": "red" }, { "k": "price"."v": 150} {}]"_id": 2."array": [{ "k": "color"."v": "blue" }, { "k": "price"."v": 50}}]Copy the code

range

Returns a generated sequence of numbers. Given a start value, an end value, and a non-zero step size, range returns a sequence of increments from the start value to the given step size, but not the end value.

API
db.command.aggregate.range([<start>.<end>.<non-zero step>])
Copy the code
field instructions
start Start value, an expression that can be parsed as an integer
end End value, an expression that can be parsed as an integer
non-zero step Optional, step size, an expression that can be resolved to a non-zero integer, default is 1
The sample

Collection STATS has the following records:

{ "_id": 1."max": 52 }
{ "_id": 2."max": 38 }
Copy the code
const $ = db.command.aggregate
db.collection('stats').aggregate()
  .project({
    points: $.range([0.'$max'.10])}).end(a)Copy the code

Results:

{ "_id": 1."points": [0.10.20.30.40.50]} {"_id": 2."points": [0.10.20]}Copy the code

reduce

The javascript-like reduce method.

API
db.command.aggregate.reduce({
  input: <array>
  initialValue: <expression>.in: <expression>
})
Copy the code
field instructions
input The input array can be any expression that resolves to an array
initialValue The initial value
in An expression that applies to each element. There are two variables available in in. Value is the cumulative value and this is the element of the current array
The sample

Simple string concatenation

The set player has the following records:

{ "_id": 1."fullname": [ "Stephen"."Curry"]}Copy the code

Get each Player’s full name and prefix it with Player: :

const $ = db.command.aggregate
db.collection('player').aggregate()
  .project({
    info: $.reduce({
      input: '$fullname',
      initialValue: 'Player:'.in: $.concat(['$$value'.' '.'$$this']),})}).end(a)Copy the code

Returns the following:

{ "_id": 1."info": "Player: Stephen Curry" }
Copy the code

Without prefix:

const $ = db.command.aggregate
db.collection('player').aggregate()
  .project({
    name: $.reduce({
      input: '$fullname',
      initialValue: ' '.in: $.concat([
        '$$value',
        $.cond({
          if: $.eq(['$$value'.' ']),
          then: ' '.else: ' ',}).'$$this',]),})}).end(a)Copy the code

Results:

{ "_id": 1."name": "Stephen Curry" }
Copy the code

reverseArray

Returns the inverted form of the given array.

API
db.command.aggregate.reverseArray(<array>)
Copy the code

Parameters are arbitrarily resolved to array expressions.

The sample

Collection STATS has the following records:

{
  "_id": 1."sales": [ 1.2.3.4.5]}Copy the code

Take sales in reverse order:

const $ = db.command.aggregate
db.collection('stats').aggregate()
  .project({
    reversed: $.reverseArray('$sales'),}).end(a)Copy the code

Results:

{ "_id": 1."reversed": [5.4.3.2.1]}Copy the code

size

Returns the length of the array.

API
db.command.aggregate.size(<array>)
Copy the code


can be any expression that resolves to an array.

The sample

Collection shops are as follows:

{ "_id": 1."staff": [ "John"."Middleton"."George"]}Copy the code

Calculate the number of employees in each store:

const $ = db.command.aggregate
db.collection('staff').aggregate()
  .project({
    totalStaff: $.size('$staff')}).end(a)Copy the code

Results:

{ "_id": 1."totalStaff": 3 }
Copy the code

slice

Slice method similar to JavaScritp. Returns the specified subset of the given array.

API

There are two kinds of syntax:

Returns n elements starting at the beginning or end:

db.command.aggregate.slice([<array>.<n>])
Copy the code

Returns n elements counted from the beginning, back, or forward of the array at the specified position:

db.command.aggregate.slice([<array>.<position>.<n>])
Copy the code


can be any expression that resolves to an array.

can be any expression that resolves to an integer. If it is positive, the array begins with the element of the array; Slice returns an empty array if is longer than the array length. If it is negative, the array begins with the element in the penultimate ; If the absolute value of is greater than the length of the array, the start position is the start of the array.


can be any expression that resolves to an integer. If is provided,

must be a positive integer. If positive, slice returns the first n elements. If it is negative, slice returns the last n elements.

The sample

The collection of people has the following records:

{ "_id": 2."hobbies": [ "golf"."handball"]}Copy the code

Unity returns to the first two hobbies:

const $ = db.command.aggregate
db.collection('fruits').aggregate()
  .project({
    hobbies: $.slice(['$hobbies'.2]),}).end(a)Copy the code

Results:

{ "_id": 2."hobbies": [ "golf"."handball"]}Copy the code

zip

Assemble the elements of the same serial number in the second two-dimensional array of the two-dimensional array into a new array and then assemble a new two-dimensional array. As to the [[1, 2, 3], [” a “, “b”, “c”]] into [[1, “a”], [2, “b”], [3, “c”]].

API
db.command.aggregate.zip({
  inputs: [<array1>.<array2>. ] , useLongestLength:<boolean>,
  defaults: <array>
})
Copy the code

Inputs are a two-dimensional array in which the expression for each element (this can be a field reference) can be resolved as an array. If either expression returns null, < Inputs > also returns NULL. If either expression does not point to a valid field/resolves to an array/resolves to NULL, an error is returned.

UseLongestLength Determines whether the length of the output array is the longest array in the input array. The default is false, where the length of the shortest array in the input array is the length of each element in the output array.

Defaults is an array that specifies the default values for the elements of an array if the input array is of different lengths. If you specify this field, you must specify useLongestLength, otherwise an error is returned. If useLongestLength is true but defaults is empty or not specified, zip uses NULL as the default value for array elements. The length of the defaults array must be the maximum length of the input array when specifying the default values for each element.

The sample

Collection STATS has the following records:

{ "_id": 1."zip1": [1.2]."zip2": [3.4]."zip3": [5.6]}
{ "_id": 3."zip1": [1.2]."zip2": [3]}
Copy the code

Only the inputs

const $ = db.command.aggregate
db.collection('items').aggregate()
  .project({
    zip: $.zip({
      inputs: [
        '$zip1'.//Field reference'$zip2'.'$zip3',],})}).end(a)Copy the code

Results:

{ "_id": 1."zip": [[1.3.5], [2.4.6]]} {"_id": 3."zip": null }
Copy the code

Set the useLongestLength

If useLongestLength is true:

const $ = db.command.aggregate
db.collection('items').aggregate()
  .project({
    zip: $.zip({
      inputs: [
        '$zip1'.//Field reference'$zip2'.'$zip3',
      ],
      useLongestLength: true,})}).end(a)Copy the code

Results:

{ "_id": 1."zip": [[1.3.5], [2.4.6]]} {"_id": 2."zip": [[1.3.4], [2.null.5], [null.null.6]]}Copy the code

Set the defaults

const $ = db.command.aggregate
db.collection('items').aggregate()
  .project({
    zip: $.zip({
      inputs: [
        '$zip1'.//Field reference'$zip2'.'$zip3',
      ],
      useLongestLength: true,
      defaults: [- 300..- 200..- 100.],})}).end(a)Copy the code

Results:

{ "_id": 1."zip": [[1.3.5], [2.4.6]]} {"_id": 2."zip": [[1.3.4], [2.- 200..5], [- 300..- 200..6]]}Copy the code

Boolean operator

and

Given multiple expressions, and returns true only if all expressions return true, and false otherwise.

API
db.command.aggregate.and([<expression1>.<expression2>. ] )Copy the code

If the expression returns false, NULL, 0, or undefined, the expression is resolved to false; otherwise, all other returns are considered true.

The sample

Set price has the following records:

{ "_id": 1."min": 10."max": 100 }
Copy the code

Min is greater than or equal to 30 and Max is less than or equal to 80.

const $ = db.command.aggregate
db.collection('price').aggregate()
  .project({
    fullfilled: $.and([$.gte(['$min'.30]), $.lte(['$max'.80]])}).end(a)Copy the code

Results:

{ "_id": 1."fullfilled": false }
Copy the code

not

Given an expression, not returns false if the expression returns true, and true otherwise. Note that expressions cannot be logical expressions (and, OR, nor, or not).

API
db.command.aggregate.not(<expression>)
Copy the code

If the expression returns false, NULL, 0, or undefined, the expression is resolved to false; otherwise, all other returns are considered true.

The sample

The set price has the following:

{ "_id": 1."min": 10."max": 100 }
Copy the code

Find that min is not greater than 40.

const $ = db.command.aggregate
db.collection('price').aggregate()
  .project({
    fullfilled: $.not($.gt(['$min'.40))}).end(a)Copy the code

Results:

{ "_id": 1."fullfilled": true }
Copy the code

or

Given multiple expressions, OR returns true if any of them returns true, false otherwise.

API
db.command.aggregate.or([<expression1>.<expression2>. ] )Copy the code

If the expression returns false, NULL, 0, or undefined, the expression is resolved to false; otherwise, all other returns are considered true.

The sample

The set price has the following:

{ "_id": 2."min": 60."max": 80 }
{ "_id": 3."min": 30."max": 50 }
Copy the code

Find min less than 40 and Max greater than 60.

const $ = db.command.aggregate
db.collection('price').aggregate()
  .project({
    fullfilled: $.or([$.lt(['$min'.30]), $.gt(['$max'.60]])}).end(a)Copy the code

Results:

{ "_id": 2."fullfilled": false }
{ "_id": 3."fullfilled": true }
Copy the code

Comparison operator

cmp

Given two values, return their comparison values:

API

If the first value is less than the second value, return -1 if the first value is greater than the second value, return 1 if the two values are equal, return 0

db.command.aggregate.cmp([<expression1>.<expression2>])
Copy the code
The sample

Set price has the following records:

{ "_id": 1."shop1": 10."shop2": 100 }
{ "_id": 2."shop1": 80."shop2": 20 }
{ "_id": 3."shop1": 50."shop2": 50 }
Copy the code

Shop1 and SHOP2 for each item price comparison.

const $ = db.command.aggregate
db.collection('price').aggregate()
  .project({
    compare: $.cmp(['$shop1'.'$shop2'))}).end(a)Copy the code

Results:

{ "_id": 1."compare": - 1 }
{ "_id": 2."compare": 1 }
{ "_id": 3."compare": 0 }
Copy the code

eq

Matches two values, returning true if they are equal, false otherwise.

API
db.command.aggregate.eq([<value1>.<value2>])
Copy the code
The sample

Set price has the following records:

{ "_id": 1."value": 10 }
{ "_id": 2."value": 80 }
{ "_id": 3."value": 50 }
Copy the code

Find the record whose value is 50.

const $ = db.command.aggregate
db.collection('price').aggregate()
  .project({
    matched: $.eq(['$value'.50])}).end(a)Copy the code

Results:

{ "_id": 1."matched": false }
{ "_id": 2."matched": false }
{ "_id": 3."matched": true }
Copy the code

gt

Matches two values, returning true if the former is greater than the latter, false otherwise.

API
db.command.aggregate.gt([<value1>.<value2>])
Copy the code
The sample

Set price has the following records:

{ "_id": 1."value": 10 }
{ "_id": 2."value": 80 }
Copy the code

Check whether the value is greater than 50.

const $ = db.command.aggregate
db.collection('price').aggregate()
  .project({
    matched: $.gt(['$value'.50])}).end(a)Copy the code

Results:

{ "_id": 1."matched": false }
{ "_id": 2."matched": true }
Copy the code

gte

Matches two values, returning true if the former is greater than or equal to the latter, false otherwise.

API
db.command.aggregate.gte([<value1>.<value2>])
Copy the code
The sample

Set price has the following records:

{ "_id": 1."value": 10 }
{ "_id": 2."value": 80 }
{ "_id": 3."value": 50 }
Copy the code

Check whether value is greater than or equal to 50.

const $ = db.command.aggregate
db.collection('price').aggregate()
  .project({
    matched: $.gte(['$value'.50])}).end(a)Copy the code

Results:

{ "_id": 1."matched": false }
{ "_id": 2."matched": true }
{ "_id": 3."matched": true }
Copy the code

lt

Matches two values, returning true if the former is less than the latter, false otherwise.

API
db.command.aggregate.lt([<value1>.<value2>])
Copy the code
The sample

Set price has the following records:

{ "_id": 1."value": 10 }
{ "_id": 2."value": 80 }
{ "_id": 3."value": 50 }
Copy the code

Check whether the value is less than 50.

const $ = db.command.aggregate
db.collection('price').aggregate()
  .project({
    matched: $.lt(['$value'.50])}).end(a)Copy the code

Results:

{ "_id": 1."matched": true }
{ "_id": 2."matched": false }
{ "_id": 3."matched": false }
Copy the code

lte

Matches two values, returning true if the former is less than or equal to the latter, false otherwise.

API
db.command.aggregate.lte([<value1>.<value2>])
Copy the code
The sample

Set price has the following records:

{ "_id": 1."value": 10 }
{ "_id": 2."value": 80 }
{ "_id": 3."value": 50 }
Copy the code

Check whether the value is less than 50.

const $ = db.command.aggregate
db.collection('price').aggregate()
  .project({
    matched: $.lte(['$value'.50])}).end(a)Copy the code

Results:

{ "_id": 1."matched": true }
{ "_id": 2."matched": false }
{ "_id": 3."matched": true }
Copy the code

neq

Matches two values, returning true if they are not equal, false otherwise.

API
db.command.aggregate.neq([<value1>.<value2>])
Copy the code
The sample

Set price has the following records:

{ "_id": 1."value": 10 }
{ "_id": 2."value": 80 }
{ "_id": 3."value": 50 }
Copy the code

Find the record whose value is not equal to 50.

const $ = db.command.aggregate
db.collection('price').aggregate()
  .project({
    matched: $.neq(['$value'.50])}).end(a)Copy the code

Results:

{ "_id": 1."matched": true }
{ "_id": 2."matched": true }
{ "_id": 3."matched": false }
Copy the code

Conditional operator

cond

Computes a Boolean expression that returns one of the specified two values.

API

Cond can be used as follows:

cond({ if: <Boolean expression>.then: <The true value>.else: <False value>  })

cond([ <Boolean expression>.<The true value>.<False value> ])
Copy the code

In both forms, three arguments (if, then, else) are required.

$cond returns < true > if Boolean expression is true, < false > otherwise

The sample

The record of the collection items is as follows:

{ "_id": "0"."name": "item-a"."amount": 100 }
{ "_id": "1"."name": "item-b"."amount": 200 }
{ "_id": "2"."name": "item-c"."amount": 300 }
Copy the code

You can use cond to generate a new field discount based on the amount field:

const $ = db.command.aggregate
db.collection('items').aggregate()
  .project({
    name: 1,
    discount: $.cond({
        if: $.gte(['$amount'.200]),
        then: 0.7.else: 0.9})}).end(a)Copy the code

Results:

{ "_id": "0"."name": "item-a"."discount": 0.9 }
{ "_id": "1"."name": "item-b"."discount": 0.7 }
{ "_id": "2"."name": "item-c"."discount": 0.7 }
Copy the code

ifNull

Evaluates the given expression, and returns a substitute value if the expression is null, undefined, or nonexistent. Otherwise return the original value.

API
ifNull([ <expression>.<Replacement value> ])
Copy the code
The sample

The record of the collection items is as follows:

{ "_id": "0"."name": "A"."description": So this is good A. }
{ "_id": "1"."name": "B"."description": null }
{ "_id": "2"."name": "C" }
Copy the code

You can use ifNull to add an alternative value for documents that do not have a DESC field, or for documents where desc is null.

const $ = db.command.aggregate
db.collection('items').aggregate()
  .project({
    _id: 0,
    name: 1,
    description: $.ifNull(['$description'.'Commodity Description Vacancy'])}).end(a)Copy the code

Results:

{ "name": "A"."description": So this is good A. }
{ "name": "B"."description": "Product Description Vacancy" }
{ "name": "C"."description": "Product Description Vacancy" }
Copy the code

switch

Calculate the return value based on the given switch-case-default,

API
switch({
    branches: [
        case: <expression>.then: <expression>.case: <expression>.then: <expression>. ] .default: <expression>
})
Copy the code
The sample

The record of the collection items is as follows:

{ "_id": "0"."name": "item-a"."amount": 100 }
{ "_id": "1"."name": "item-b"."amount": 200 }
{ "_id": "2"."name": "item-c"."amount": 300 }
Copy the code

You can use the switch to generate a new field discount based on the amount field:

const $ = db.command.aggregate
db.collection('items').aggregate()
  .project({
    name: 1,
    discount: $.switch({
        branches: [
            { case: $.gt(['$amount'.250]), then: 0.8 },
            { case: $.gt(['$amount'.150]), then: 0.9}].default: 1})}).end(a)Copy the code

Results:

{ "_id": "0"."name": "item-a"."discount": 1 }
{ "_id": "1"."name": "item-b"."discount": 0.9 }
{ "_id": "2"."name": "item-c"."discount": 0.8 }
Copy the code

Date operator

dateFromParts

Builds and returns a date object for a given date.

API
db.command.aggregate.dateFromParts({
    year: <year>.month: <month>.day: <day>.hour: <hour>.minute: <minute>.second: <second>,
    millisecond: <ms>,
    timezone: <tzExpression>
})
Copy the code

You can also use the ISO 8601 standard:

db.command.aggregate.dateFromParts({
    isoWeekYear: <year>,
    isoWeek: <week>,
    isoDayOfWeek: <day>.hour: <hour>.minute: <minute>.second: <second>,
    millisecond: <ms>,
    timezone: <tzExpression>
})
Copy the code

instructions

  • timezoneFields please refer toOlson Timezone IdentifierIn a similar form:Asia/Shanghai
The sample
const $ = db.command.aggregate
db
  .collection('dates')
  .aggregate()
  .project({
    _id: 0.date: $.dateFromParts({
        year: 2017.month: 2.day: 8.hour: 12,
        timezone: 'America/New_York'}})).end(a)Copy the code

Results:

{
    "date": ISODate("The 2017-02-08 T17:00:00) 000 z")}Copy the code

dateFromString

Converts a date/time string to a date object

API
db.command.aggregate.dateFromString({
    dateString: <dateStringExpression>,
    timezone: <tzExpression>
})
Copy the code
The sample
const $ = db.command.aggregate
db
  .collection('dates')
  .aggregate()
  .project({
    _id: 0.date$.dateFromString({dateString: "2019-05-14T09:38:51.686z"})})end(a)Copy the code

Results:

{
    "date": ISODate("The 2019-05-14 T09:38:51. 686 z")}Copy the code

dateToString

Formats a date object into a string based on the specified expression.

API
db.command.aggregate.dateToString({
  date: <Date expression>,
  format: <Formatted expression>,
  timezone: <Time zone expression>,
  onNull: <Null valued expression>
})
Copy the code

Here are the four expressions in detail:

The name of the describe
Date expression Will be selected. Specifies that the field value should be a date that can be converted to a string.
Formatted expression Optional. It can be any valid string that contains a format specifier.
Time zone expression Optional. Specifies the time zone of the result. It can be parsed in format asUTC OffsetorOlson Timezone IdentifierString of.
Null valued expression Optional. When the < date expression > returns empty or does not exist, the value specified by the expression is returned.

Here is a detailed description of the format specifier:

specifier describe Legal values
%d Date of month (2-digit, 0 filled) 01-31
%G The year is in ISO 8601 format 0000-9999.
%H Hours (2-digit, 0-filled, 24-hour system) 00-23
%j Day of the year (3-digit, 0 filled) 001-366.
%L Ms (3 digits, 0 filled) 000-999.
%m Month (2-digit, 0 filled) 01-12
%M Minutes (2 digits, 0 filled) 00-59
%S Seconds (2 digits, 0 filled) 00-60
%w What day 1-7
%u Day of the week in ISO 8601 format 1-7
%U Week of the year (2 digits filled with 0) 00-53
%V Week of the year in ISO 8601 format 1-53
%Y Year (4 digits filled with 0) 0000-9999.
%z The time zone offset from UTC +/-[hh][mm]
%Z The time zone offset from UTC, in minutes +/-mmm
% % Percentage sign as character %
The sample

Set students have the following records:

{ "date": "The 1999-12-11 T16:00:00) 000 z"."firstName": "Yuanxin"."lastName": "Dong" }
Copy the code

Formatting date

Here’s how to format the date field into a year-month-day string:

const $ = db.command.aggregate
db
  .collection('students')
  .aggregate()
  .project({
    _id: 0,
    formatDate: $.dateToString({
      date: '$date',
      format: '%Y-%m-%d'})}).end(a)Copy the code

Result returned:

{ "formatDate": "1999-12-11" }
Copy the code

Time zone

Here is an example of formatting the date field to the Shanghai time zone:

const $ = db.command.aggregate
db
  .collection('students')
  .aggregate()
  .project({
    _id: 0,
    formatDate: $.dateToString({
      date: '$date',
      format: '%H:%M:%S',
      timezone: 'Asia/Shanghai'})}).end(a)Copy the code

Results:

{ "formatDate": "00:00:00" }
Copy the code

Default value for missing cases

The default value can be set when the specified < date expression > returns null or does not exist:

const $ = db.command.aggregate
db
  .collection('students')
  .aggregate()
  .project({
    _id: 0,
    formatDate: $.dateToString({
      date: '$empty',
      onNull: 'null'})}).end(a)Copy the code

Results:

{ "formatDate": "null" }
Copy the code

dayOfMonth

Returns the day (day of the month) for the date field, a number between 1 and 31.

API
db.command.aggregate.dayOfMonth(<Date fields>)
Copy the code
The sample

Set Dates has the following documents:

{
    "_id": 1."date": ISODate("The 2019-05-14 T09:38:51. 686 z")}Copy the code

Use dayOfMonth() to project the date field and get the corresponding date:

const $ = db.command.aggregate
db
  .collection('dates')
  .aggregate()
  .project({
    _id: 0,
    dayOfMonth: $.dayOfMonth('$date')}).end(a)Copy the code

Results:

{
    "dayOfMonth": 14
}
Copy the code

dayOfWeek

Returns the day (day of the week) for the date field, an integer between 1 (Sunday) and 7 (Saturday).

API

Note: Sunday is the first day of the week *

db.command.aggregate.dayOfWeek(<Date fields>)
Copy the code
The sample

Set Dates has the following documents:

{
    "_id": 1."date": ISODate("The 2019-05-14 T09:38:51. 686 z")}Copy the code

DayOfWeek (); dayOfWeek(); dayOfWeek(); dayOfWeek()

const $ = db.command.aggregate
db
  .collection('dates')
  .aggregate()
  .project({
    _id: 0,
    dayOfWeek: $.dayOfWeek('$date')}).end(a)Copy the code

Results:

{
    "dayOfWeek": 3
}
Copy the code

dayOfYear

Returns the number of days (days of the year) corresponding to the date field, an integer between 1 and 366.

API
db.command.aggregate.dayOfYear(<Date fields>)
Copy the code
The sample

Set Dates has the following documents:

{
    "_id": 1."date": ISODate("The 2019-05-14 T09:38:51. 686 z")}Copy the code

DayOfYear (); dayOfYear(); dayOfYear();

const $ = db.command.aggregate
db
  .collection('dates')
  .aggregate()
  .project({
    _id: 0,
    dayOfYear: $.dayOfYear('$date')}).end(a)Copy the code

Results:

{
    "dayOfYear": 134
}
Copy the code

hour

Returns the number of hours corresponding to the date field, an integer between 0 and 23.

API
db.command.aggregate.hour(<Date fields>)
Copy the code
The sample

Set Dates has the following documents:

{
    "_id": 1."date": ISODate("The 2019-05-14 T09:38:51. 686 z")}Copy the code

Cast a shadow on the date field using hour() to get the corresponding number of hours:

const $ = db.command.aggregate
db
  .collection('dates')
  .aggregate()
  .project({
    _id: 0.hour: $.hour('$date')}).end(a)Copy the code

Results:

{
    "hour": 9
}
Copy the code

isoDayOfWeek

The ISO 8601 standard day (day of the week) for which the return date field corresponds is an integer between 1 (Monday) and 7 (Sunday).

API
db.command.aggregate.month(<Date fields>)
Copy the code
The sample

Set Dates has the following documents:

{
    "_id": 1."date": ISODate("The 2019-05-14 T09:38:51. 686 z")}Copy the code

Use month() to project the date field to the ISO 8601 standard number of days in a week:

const $ = db.command.aggregate
db
  .collection('dates')
  .aggregate()
  .project({
    _id: 0,
    isoDayOfWeek: $.isoDayOfWeek('$date')}).end(a)Copy the code

Results:

{
    "isoDayOfWeek": 2
}
Copy the code

isoWeek

The ISO 8601 week (the week of the year) for which the date field corresponds is an integer between 1 and 53.

API

According to ISO 8601, Monday to Sunday is regarded as a week, and the week of the first Thursday of the current year is regarded as the first week of the current year.

For example, January 7, 2016 is the first Thursday of the year, so January 04, 2016 (Monday) to October 10, 2016 (Sunday) are the first week. Similarly, the number of weeks on January 1, 2016 was 53.

db.command.aggregate.isoWeek(<Date fields>)
Copy the code
The sample

Set Dates has the following documents:

{
    "_id": 1."date": ISODate("The 2019-05-14 T09:38:51. 686 z")}Copy the code

Use isoWeek() to project the date field and get the corresponding ISO 8601 standard week (week of the year) :

const $ = db.command.aggregate
db
  .collection('dates')
  .aggregate()
  .project({
    _id: 0,
    isoWeek: $.isoWeek('$date')}).end(a)Copy the code

Results:

{
    "isoWeek": 20
}
Copy the code

isoWeekYear

Returns the number of days (days of the year) of the ISO 8601 standard corresponding to the date field.

API

The year begins on the Monday of the first week and ends on the Sunday of the last week.

db.command.aggregate.isoWeekYear(<Date fields>)
Copy the code
The sample

Set Dates has the following documents:

{
    "_id": 1."date": ISODate("The 2019-05-14 T09:38:51. 686 z")}Copy the code

Use isoWeekYear() to project the date field to the ISO 8601 standard number of days in a year:

const $ = db.command.aggregate
db
  .collection('dates')
  .aggregate()
  .project({
    _id: 0,
    isoWeekYear: $.isoWeekYear('$date')}).end(a)Copy the code

Results:

{
    "isoWeekYear": 2019
}
Copy the code

millisecond

Returns the number of milliseconds corresponding to the date field, which is an integer between 0 and 999.

API
db.command.aggregate.millisecond(<Date fields>)
Copy the code
The sample

Set Dates has the following documents:

{
    "_id": 1."date": ISODate("The 2019-05-14 T09:38:51. 686 z")}Copy the code

Date (millisecond())

const $ = db.command.aggregate
db
  .collection('dates')
  .aggregate()
  .project({
    _id: 0,
    millisecond: $.millisecond('$date'),}).end(a)Copy the code

Results:

{
    "millisecond": 686
}
Copy the code

minute

Returns the number of minutes corresponding to the date field, which is an integer between 0 and 59.

API
db.command.aggregate.minute(<Date fields>)
Copy the code
The sample

Set Dates has the following documents:

{
    "_id": 1."date": ISODate("The 2019-05-14 T09:38:51. 686 z")}Copy the code

Use minute() to project the date field and get the corresponding number of minutes:

const $ = db.command.aggregate
db
  .collection('dates')
  .aggregate()
  .project({
    _id: 0.minute: $.minute('$date')}).end(a)Copy the code

Results:

{
    "minute": 38
}
Copy the code

month

Returns the month of the date field, which is an integer between 1 and 12.

API
db.command.aggregate.month(<Date fields>)
Copy the code
The sample

Set Dates has the following documents:

{
    "_id": 1."date": ISODate("The 2019-05-14 T09:38:51. 686 z")}Copy the code

Use month() to project the date field and get the month:

const $ = db.command.aggregate
db
  .collection('dates')
  .aggregate()
  .project({
    _id: 0.month: $.month('$date')}).end(a)Copy the code

Results:

{
    "month": 5
}
Copy the code

second

Return the number of seconds corresponding to the date field, which is an integer between 0 and 59, or 60 in special cases (leap seconds).

API
db.command.aggregate.second(<Date fields>)
Copy the code
The sample

Set Dates has the following documents:

{
    "_id": 1."date": ISODate("The 2019-05-14 T09:38:51. 686 z")}Copy the code

Use second() to project the date field and get the corresponding number of seconds:

const $ = db.command.aggregate
db
  .collection('dates')
  .aggregate()
  .project({
    _id: 0.second: $.second('$date')}).end(a)Copy the code

Results:

{
    "second": 51
}
Copy the code

week

Returns the number of weeks (days of the year) corresponding to the date field, an integer between 0 and 53.

API

Each week starts with Sunday. Week 1 starts on the first Sunday of each year, and week 0 precedes this day.

db.command.aggregate.week(<Date fields>)
Copy the code
The sample

Set Dates has the following documents:

{
    "_id": 1."date": ISODate("The 2019-05-14 T09:38:51. 686 z")}Copy the code

Use week() to project the date field to the week of the year:

const $ = db.command.aggregate
db
  .collection('dates')
  .aggregate()
  .project({
    _id: 0,
    week: $.week('$date')}).end(a)Copy the code

Results:

{
    "week": 19
}
Copy the code

year

Returns the year of the date field.

API
db.command.aggregate.year(<Date fields>)
Copy the code
The sample

Set Dates has the following documents:

{
    "_id": 1."date": ISODate("The 2019-05-14 T09:38:51. 686 z")}Copy the code

Use year() to cast a projection on the date field and get the corresponding year:

const $ = db.command.aggregate
db
  .collection('dates')
  .aggregate()
  .project({
    _id: 0.year: $.year('$date')}).end(a)Copy the code

Results:

{
    "year": 2019
}
Copy the code

subtract

See you subtract

Constant operator

literal

Returns a literal value directly, without any parsing or processing.

API
literal(<value>)
Copy the code

If < value > is an expression, the LITERAL does not parse or evaluate the expression, but returns it directly.

The sample

For example, we have an items collection with the following data:

{ "_id": "0"."price": "$1" }
{ "_id": "1"."price": "$5.60" }
Copy the code

Use $as a literal

Using literal, the following code generates a new field, isOneDollar, indicating whether the price field is strictly equal to “$1”.

Note: eq([‘$price’, ‘$1’]) cannot be used here because “$1” is an expression representing the value of the “1” field, not the string literal “$1”.

const $ = db.command.aggregate
db.collection('items').aggregate()
  .project({
    isOneDollar: $.eq(['$price', $.literal('$1')])}).end(a)Copy the code

Results:

{ "_id": "0"."isOneDollar": true }
{ "_id": "1"."isOneDollar": false }
Copy the code

Project a field with a value of 1

The following code, using literal, projects a new field, amount, with a value of 1.

const $ = db.command.aggregate
db.collection('items').aggregate()
  .project({
    price: 1,
    amount: $.literal(1)}).end(a)Copy the code

Results:

{ "_id": "0"."price": "$1"."amount": 1 }
{ "_id": "1"."price": "$5.60"."amount": 1 }
Copy the code

Object operator

mergeObjects

Combine multiple documents into a single document.

API

When used in group() :

mergeObjects(<document>)
Copy the code

When used in other expressions:

mergeObjects([<document1>.<document2>. ] )Copy the code
The sample

collocationgroup()use

The collection SALES has the following documentation:

{ "_id": 1."year": 2018."name": "A"."volume": { "2018Q1": 500."2018Q2": 500}} {"_id": 2."year": 2017."name": "A"."volume": { "2017Q1": 400."2017Q2": 300."2017Q3": 0."2017Q4": 0}} {"_id": 3."year": 2018."name": "B"."volume": { "2018Q1": 100}} {"_id": 4."year": 2017."name": "B"."volume": { "2017Q3": 100."2017Q4": 250}}Copy the code

The following code uses mergeObjects() to merge documents with the same name:

const $ = db.command.aggregate
db.collection('sales').aggregate()
  .group({
    _id: '$name',
    mergedVolume: $.mergeObjects('$volume')}).end(a)Copy the code

Results:

{ "_id": "A"."mergedVolume": { "2017Q1": 400."2017Q2": 300."2017Q3": 0."2017Q4": 0."2018Q1": 500."2018Q2": 500}} {"_id": "B"."mergedVolume": { "2017Q3": 100."2017Q4": 250."2018Q1": 100}}Copy the code

General usage

The collection test exists with the following documents:

{ "_id": 1."foo": { "a": 1 }, "bar": { "b": 2}} {"_id": 2."foo": { "c": 1 }, "bar": { "d": 2}} {"_id": 3."foo": { "e": 1 }, "bar": { "f": 2}}Copy the code

The following code uses mergeObjects() to merge the foo and bar fields in the document into foobar:

const $ = db.command.aggregate
db.collection('sales').aggregate()
  .project({
    foobar: $.mergeObjects(['$foo'.'$bar'])}).end(a)Copy the code

Results:

{ "_id": 1."foobar": { "a": 1."b": 2}} {"_id": 2."foobar": { "c": 1."d": 2}} {"_id": 3."foobar": { "e": 1."f": 2}}Copy the code

objectToArray

See objectToArray

Set operator

allElementsTrue

Enter an array, or an expression for an array field. Return true if all elements in the array are true, false otherwise. An empty array always returns true.

API
allElementsTrue([<expression>])
Copy the code
The sample

The set test has the following records:

{ "_id": 1."array": [ true]} {"_id": 2."array": []} {"_id": 3."array": [ false]} {"_id": 4."array": [ true.false]} {"_id": 5."array": [ 0]} {"_id": 6."array": [ "stark"]}Copy the code

The following code uses allElementsTrue() to determine whether all values in the array field are true:

const $ = db.command.aggregate
db.collection('price')
  .aggregate()
  .project({
    isAllTrue: $.allElementsTrue(['$array'])}).end(a)Copy the code

Results:

{ "_id": 1."isAllTrue": true }
{ "_id": 2."isAllTrue": true }
{ "_id": 3."isAllTrue": false }
{ "_id": 4."isAllTrue": false }
{ "_id": 5."isAllTrue": false }
{ "_id": 6."isAllTrue": true }
Copy the code

setDifference

The aggregate operator, which takes two sets and outputs only the elements that exist in the first set.

API
setDifference([<expression1>.<expression2>])
Copy the code
The sample

The test collection has the following data:

{ "_id": 1."A": [ 1.2]."B": [ 1.2]} {"_id": 2."A": [ 1.2]."B": [ 2.1.2]} {"_id": 3."A": [ 1.2]."B": [ 1.2.3]} {"_id": 4."A": [ 1.2]."B": [ 3.1]} {"_id": 5."A": [ 1.2]."B": []} {"_id": 6."A": [ 1.2]."B": [{}, []]} {"_id": 7."A": []."B": []} {"_id": 8."A": []."B": [ 1]}Copy the code

The following code uses setDifference to find numbers that only exist in B:

db.collection('test')
  .aggregate()
  .project({
    isBOnly: $.setDifference(['$B'.'$A'])}).end(a)Copy the code
{ "_id": 1."isBOnly": []} {"_id": 2."isBOnly": [3]} {"_id": 3."isBOnly": [3]} {"_id": 4."isBOnly": [5]} {"_id": 5."isBOnly": []} {"_id": 6."isBOnly": [{}, []]} {"_id": 7."isBOnly": []} {"_id": 8."isBOnly": [1]}Copy the code

setIntersection

Aggregate operator that takes two sets and outputs the intersection of two sets.

API
setIntersection([<expression1>.<expression2>])
Copy the code
The sample

The test collection has the following data:

{ "_id": 2."A": [ 1.2]."B": [ 2.1.2]} {"_id": 3."A": [ 1.2]."B": [ 1.2.3]} {"_id": 4."A": [ 1.2]."B": [ 3.1]}Copy the code

The following code uses setIntersection to print the intersection of two collections:

db.collection('test')
  .aggregate()
  .project({
    commonToBoth: $.setIntersection(['$A'.'$B'])}).end(a)Copy the code

Results:

{ "_id": 2."commonToBoth": [ 1.2]} {"_id": 3."commonToBoth": [ 1.2]} {"_id": 4."commonToBoth": [ 1]}Copy the code

setIsSubset

The aggregate operator, which takes two sets and determines whether the first set is a subset of the second.

API
setIsSubset([<expression1>.<expression2>])
Copy the code
The sample

The test collection has the following data:

{ "_id": 2."A": [ 1.2]."B": [ 2.1.2]} {"_id": 3."A": [ 1.2]."B": [ 1.2.3]} {"_id": 4."A": [ 1.2]."B": [ 3.1]}Copy the code

The following code uses settis subset to determine whether the first set is a subset of the second set:

db.collection('test')
  .aggregate()
  .project({
    AisSubsetOfB: $.setIsSubset(['$A'.'$B'])}).end(a)Copy the code
{ "_id": 2."AisSubsetOfB": true }
{ "_id": 3."AisSubsetOfB": true }
{ "_id": 4."AisSubsetOfB": false }
Copy the code

setUnion

The aggregate operator, which inputs two sets and outputs the union of two sets.

API
setUnion([<expression1>.<expression2>])
Copy the code
The sample

The test collection has the following data:

{ "_id": 2."A": [ 1.2]."B": [ 2.1.2]} {"_id": 6."A": [ 1.2]."B": [{}, []]} {"_id": 7."A": []."B": []} {"_id": 8."A": []."B": [ 1]}Copy the code

The following code uses setUnion to print the union of two sets:

db.collection('test')
  .aggregate()
  .project({
    AB: $.setUnion(['$A'.'$B'])}).end(a)Copy the code

Results:

{ "_id": 1."AB": [ 1.2]} {"_id": 2."AB": [ 1.2]} {"_id": 6."AB": [ 1.2, {}, []]} {"_id": 7."AB": []} {"_id": 8."AB": [ 1]}Copy the code

String operator

concat

Concatenate string, returns the concatenated string.

API
db.command.aggregate.concat([<expression1>.<expression2>. ] )Copy the code

The expression can be a specified field of the form $+ or a plain string. As long as it can be parsed into a string.

The sample

The record of set students is as follows:

{ "firstName": "Yuanxin"."group": "a"."lastName": "Dong"."score": 84 }
Copy the code

With concat, you can concatenate the lastName and firstName fields to get the full name of each student:

const $ = db.command.aggregate
db
  .collection('students')
  .aggregate()
  .project({
    _id: 0,
    fullName: $.concat(['$firstName'.' '.'$lastName'])}).end(a)Copy the code

Returns the following:

{ "fullName": "Yuanxin Dong" }
Copy the code

dateFromString

See dateFromString

dateToString

See dateToString

indexOfBytes

Looks for substrings in the target string and returns the byte index (starting from 0) of the first occurrence of UTF-8. Returns -1 if no substring exists.

API
db.command.aggregate.indexOfBytes([<Target string expression>.<Substring expression>.<Starting position expression>.<End position expression>])
Copy the code

The following are detailed descriptions of the four expressions:

expression describe
Target string expression Any expression that can be parsed as a string
Substring expression ~~ Expression of a string
Starting position expression ~~ is an expression of a non-negative integer
End position expression ~~ is an expression of a non-negative integer
The sample

The record of set students is as follows:

{ "firstName": "Yuanxin"."group": "a"."lastName": "Dong"."score": 84 }
Copy the code

Find the position of the character “a” in the firstName field with indexOfBytes:

const $ = db.command.aggregate
db
  .collection('students')
  .aggregate()
  .project({
    _id: 0,
    aStrIndex: $.indexOfBytes(['$firstName'.'a'])}).end(a)Copy the code

Result returned:

{ "aStrIndex": 2 }
Copy the code

indexOfCP

Looks for substrings in the target string and returns the code point index (starting from 0) of the first occurrence of UTF-8. Returns -1 if no substring exists.

API

A code point is a code point. This refers specifically to code points in Unicode packages that range from 0 (hexadecimal) to 10FFFF (hexadecimal).

db.command.aggregate.indexOfCP([<Target string expression>.<Substring expression>.<Starting position expression>.<End position expression>])
Copy the code

The following are detailed descriptions of the four expressions:

expression describe
Target string expression Any expression that can be parsed as a string
Substring expression ~~ Expression of a string
Starting position expression ~~ is an expression of a non-negative integer
End position expression ~~ is an expression of a non-negative integer
The sample

The record of set students is as follows:

{ "firstName": "Yuanxin"."group": "a"."lastName": "Dong"."score": 84 }
Copy the code

IndexOfCP find position of character “a” in firstName with indexOfCP

const $ = db.command.aggregate
db
  .collection('students')
  .aggregate()
  .project({
    _id: 0,
    aStrIndex: $.indexOfCP(['$firstName'.'a'])}).end(a)Copy the code

Result returned:

{ "aStrIndex": 2 }
Copy the code

split

Delimiting the array by delimiter and removing the delimiter returns an array of substrings. If the string cannot find a delimiter to separate it, return the original string as the unique element of the array.

API
db.command.aggregate.split([<String expression>.<Delimiter expression>])
Copy the code

String and delimiter expressions can be expressions of any form, as long as they can be parsed as strings.

The sample

Set records of students:

{ "birthday": "1999/12/12" }
Copy the code

Use split to separate the birthday field values in each record into arrays, each array consists of three elements representing year, month, and day respectively:

const $ = db.command.aggregate
db
  .collection('students')
  .aggregate()
  .project({
    _id: 0,
    birthday: $.split(['$birthday'.'/'])}).end(a)Copy the code

Result returned:

{ "birthday": [ "1999"."12"."12"]}Copy the code

strLenCP

Computes and returns the number of UTF-8 code points for the specified string.

API
db.command.aggregate.strLenCP(<expression>)
Copy the code

As long as an expression can be parsed into a string, it is a valid expression.

The sample

The record of set students is as follows:

{ "name": "dongyuanxin"."nickname": "Heart tan" }
Copy the code

Select * from utF-8 code points where strLenCP = ‘name’ and ‘nickname’ = ‘nickname’

const $ = db.command.aggregate
db
  .collection('students')
  .aggregate()
  .project({
    _id: 0,
    nameLength: $.strLenCP('$name'),
    nicknameLength: $.strLenCP('$nickname')}).end(a)Copy the code

Results:

{ "nameLength": 11."nicknameLength": 2 }
Copy the code

substr

Returns a substring of the specified length starting at the specified position of the string. It is db.com mand. Aggregate. SubstrBytes alias, it is recommended to use the latter more.

API
db.command.aggregate.substr([<expression1>.<expression2>.<expression3>])
Copy the code

Expression 1 is any valid expression that can be parsed to a string, and expressions 2 and 3 are any valid expression that can be parsed to a number.

If expression 2 is negative, the result returned is “”.

If expression 3 is negative, the result is a substring from the beginning of expression 2 and the remainder thereafter.

The sample

Set records of students:

{ "birthday": "1999/12/12"."firstName": "Yuanxin"."group": "a"."lastName": "Dong"."score": 84 }
Copy the code

Substr = birthday; substr = birthday; substr = birthday;

const $ = db.command.aggregate
db
  .collection('students')
  .aggregate()
  .project({
    _id: 0.year: $.substr(['$birthday'.0.4]),
    month: $.substr(['$birthday'.5.2]),
    day: $.substr(['$birthday'.8.- 1])}).end(a)Copy the code

Results:

{ "day": "12"."month": "12"."year": "1999" }
Copy the code

substrBytes

Returns a substring of the specified length starting at the specified position of the string. A substring starts with a character in the utF-8 byte index specified in the string and is a specified number of bytes long.

API
db.command.aggregate.substrBytes([<expression1>.<expression2>.<expression3>])
Copy the code

Expression 1 is any valid expression that can be parsed to a string, and expressions 2 and 3 are any valid expression that can be parsed to a number.

If expression 2 is negative, the result returned is “”.

If expression 3 is negative, the result is a substring from the beginning of expression 2 and the remainder thereafter.

The sample

Set records of students:

{ "birthday": "1999/12/12"."firstName": "Yuanxin"."group": "a"."lastName": "Dong"."score": 84 }
Copy the code

With substrBytes we can extract the year, month, and day from birthday:

const $ = db.command.aggregate
db
  .collection('students')
  .aggregate()
  .project({
    _id: 0.year: $.substrBytes(['$birthday'.0.4]),
    month: $.substrBytes(['$birthday'.5.2]),
    day: $.substrBytes(['$birthday'.8.- 1])}).end(a)Copy the code

Results:

{ "day": "12"."month": "12"."year": "1999" }
Copy the code

substrCP

Returns a substring of the specified length starting at the specified position of the string. A substring starts with a character in the utF-8 byte index specified in the string and is a specified number of bytes long.

API
db.command.aggregate.substrCP([<expression1>.<expression2>.<expression3>])
Copy the code

Expression 1 is any valid expression that can be parsed to a string, and expressions 2 and 3 are any valid expression that can be parsed to a number.

If expression 2 is negative, the result returned is “”.

If expression 3 is negative, the result is a substring from the beginning of expression 2 and the remainder thereafter.

The sample

The record of set students is as follows:

{ "nickname": "Heart tan" }
Copy the code

We can extract the first word of the nickname field value with substrCP:

const $ = db.command.aggregate
db
  .collection('students')
  .aggregate()
  .project({
    _id: 0,
    firstCh: $.substrCP(['$nickname'.0.1])}).end(a)Copy the code

Results:

{ "firstCh": "Heart" }
Copy the code

toLower

Converts the string to lowercase and returns.

API
Db.com mand. Aggregate. ToLower (expression)Copy the code

As long as an expression can be parsed into a string, it is a valid expression. For example, $+ specifies the field.

The sample

The record of set students is as follows:

{ "firstName": "Yuanxin"}
Copy the code

Convert firstName to lowercase with toLower:

const $ = db.command.aggregate
db
  .collection('students')
  .aggregate()
  .project({
    _id: 0.result: $.toLower('$firstName'),}).end(a)Copy the code

Results:

{ "result": "yuanxin" }
Copy the code

toUpper

Converts the string to uppercase and returns.

API
Db.com mand. Aggregate. ToUpper (expression)Copy the code

As long as an expression can be parsed into a string, it is a valid expression. For example, $+ specifies the field.

The sample

The record of set students is as follows:

{ "firstName": "Yuanxin"."lastName": "Dong"}
Copy the code

Convert lastName to uppercase with toUpper:

const $ = db.command.aggregate
db
  .collection('students')
  .aggregate()
  .project({
    _id: 0.result: $.toUpper('$lastName'),}).end(a)Copy the code

Results:

{ "result": "DONG" }
Copy the code

Accumulator operator

addToSet

Adds a value to an array without doing anything if the value already exists in the array. It can only be used in group stages.

API
db.command.aggregate.addToSet(<expression>)
Copy the code

The expression is a string of the form $+ specified field. If the value of the specified field is an array, the entire array is treated as an element.

The sample

Passages are recorded as follows:

{ "category": "web"."tags": [ "JavaScript"."CSS"]."title": "title1" }
{ "category": "System"."tags": [ "C++"."C"]."title": "title2" }
Copy the code

Non-array field

The category value of each record is of non-array type, and addToSet is used to count all categories:

const $ = db.command.aggregate
db
  .collection('passages')
  .aggregate()
  .group({
    _id: null,
    categories: $.addToSet('$category')}).end(a)Copy the code

Results:

{ "_id": null."categories": [ "System"."web"]}Copy the code

An array of fields

Tags for each record are of type array. Arrays are not automatically expanded:

const $ = db.command.aggregate
db
  .collection('passages')
  .aggregate()
  .group({
    _id: null,
    tagsList: $.addToSet('$tags')}).end(a)Copy the code

Results:

{ "_id": null."tagsList": [["C++"."C" ], [ "JavaScript"."CSS"]]}Copy the code

avg

Returns the average value of data for a specified field in a set of collections.

API
db.command.aggregate.avg(<number>)
Copy the code

In addition to numeric constants, the value passed in by AVG can be any expression that ultimately resolves to a number. It ignores non-numeric values.

The sample

The record of set students is as follows:

{ "group": "b"."name": "stu3"."score": 80 }
{ "group": "b"."name": "stu4"."score": 100 }
Copy the code

With the help of AVG, the average value of score of all records can be calculated:

const $ = db.command.aggregate
db
  .collection('students')
  .aggregate()
  .group({
    _id: null,
    average: $.avg('$score')}).end(a)Copy the code

Results:

{ "_id": null."average": 90 }
Copy the code

first

Returns the value of the first record of a specified field in a set of collections. This operation makes sense only if the set is sorted by some definition.

API
db.command.aggregate.first(<expression>)
Copy the code

The expression is a string of the form $+ specified field.

First can only be used in the group phase and needs to work with sort to make sense.

The sample

The record of set students is as follows:

{ "group": "b"."name": "stu3"."score": 80 }
{ "group": "b"."name": "stu4"."score": 100 }
Copy the code

If you need to get the minimum score of all records, you can first sort all records according to score and then extract the first of the first record.

const $ = db.command.aggregate
db
  .collection('students')
  .aggregate()
  .sort({
    score: 1}).group({
    _id: null,
    min: $.first('$score')}).end(a)Copy the code

Results:

{ "_id": null."min": 80 }
Copy the code

last

Returns the value of the last record of a specified field in a set of collections. This operation makes sense only if the set is sorted by some definition.

API
db.command.aggregate.last(<expression>)
Copy the code

The expression is a string of the form $+ specified field.

Last can only be used in the group phase and needs to work with sort to make sense.

The sample

The record of set students is as follows:

{ "group": "a"."name": "stu2"."score": 96 }
{ "group": "b"."name": "stu4"."score": 100 }
Copy the code

If you want to get the maximum score of all records, you can sort all records by score and then fetch last of the last record.

const $ = db.command.aggregate
db
  .collection('students')
  .aggregate()
  .sort({
    score: 1}).group({
    _id: null,
    max: $.last('$score')}).end(a)Copy the code

Results:

{ "_id": null."max": 100 }
Copy the code

max

Returns the maximum value of a set of values.

API
db.command.aggregate.max(<expression>)
Copy the code

The expression is a string of the form $+ specified field.

The sample

The record of set students is as follows:

{ "group": "a"."name": "stu2"."score": 96 }
{ "group": "b"."name": "stu4"."score": 100 }
Copy the code

With the help of Max, the highest score in different groups can be counted. The code is as follows:

const $ = db.command.aggregate
db
  .collection('students')
  .aggregate()
  .group({
    _id: '$group',
    maxScore: $.max('$score')}).end(a)Copy the code

Results:

{ "_id": "b"."maxScore": 100 }
{ "_id": "a"."maxScore": 96 }
Copy the code

mergeObjects

See mergeObjects

min

Returns the minimum value of a set of values.

API
db.command.aggregate.min(<expression>)
Copy the code

The expression is a string of the form $+ specified field.

The sample

The record of set students is as follows:

{ "group": "a"."name": "stu1"."score": 84 }
{ "group": "a"."name": "stu2"."score": 96 }
{ "group": "b"."name": "stu3"."score": 80 }
{ "group": "b"."name": "stu4"."score": 100 }
Copy the code

With the help of MIN, the lowest score in different groups can be counted. The code is as follows:

const $ = db.command.aggregate
db
  .collection('students')
  .aggregate()
  .group({
    _id: '$group',
    minScore: $.min('$score')}).end(a)Copy the code

Results:

{ "_id": "b"."minScore": 80 }
{ "_id": "a"."minScore": 84 }
Copy the code

push

In the group phase, returns an array of the columns specified by the expression and their corresponding values.

API
db.command.aggregate.push({
  <The field name1>: <Specified field1>.<The field name2>: <Specified field2>. })Copy the code
The sample

The record of set students is as follows:

{ "group": "a"."name": "stu1"."score": 84 }
{ "group": "a"."name": "stu2"."score": 96 }
{ "group": "b"."name": "stu3"."score": 80 }
{ "group": "b"."name": "stu4"."score": 100 }
Copy the code

With push, all records in different groups are aggregated and put into a new field to further structure and semantically define the data.

const $ = db.command.aggregate
db
  .collection('students')
  .aggregate()
  .group({
    _id: '$group',
    students: $.push({
      name: '$name',
      score: '$score'})}).end(a)Copy the code

Results:

{ "_id": "b"."students": [{ "name": "stu3"."score": 80 }, { "name": "stu4"."score": 100} {}]"_id": "a"."students": [{ "name": "stu1"."score": 84 }, { "name": "stu2"."score": 96}}]Copy the code

stdDevPop

Returns the standard deviation of the values of a set of fields.

API
db.command.aggregate.stdDevPop(<expression>)
Copy the code

The expression passes in the specified field. The value of the specified field must be of the data type number, otherwise null is returned.

The sample

Group A students’ scores are 84 and 96 respectively, and Group B students’ scores are 80 and 100 respectively.

{ "group":"a"."score":84 }
{ "group":"a"."score":96 }
{ "group":"b"."score":80 }
{ "group":"b"."score":100 }
Copy the code

StdDevPop can be used to calculate the standard deviation of the scores of group A and B, so as to compare which group’s scores are more stable. Code:

const $ = db.command.aggregate
db.collection('students').aggregate()
  .group({
    _id: '$group',
    stdDev: $.stdDevPop('$score')}).end(a)Copy the code

Results:

{ "_id": "b"."stdDev": 10 }
{ "_id": "a"."stdDev": 6 }
Copy the code

stdDevSamp

Calculate the sample standard deviation of the input values. If the input value on behalf of the general data, or no more data, please use db.com mand. Aggregate. StdDevPop.

API
db.command.aggregate.stdDevSamp(<expression>)
Copy the code

The expression passes in the specified field, and stdDevSamp automatically ignores non-numeric values. If all values of a specified field are non-numeric, null is returned.

The sample

Set records of students:

{ "score": 80 }
{ "score": 100 }
Copy the code

StdDevSamp can be used to calculate the standard sample deviation of grades. Code:

const $ = db.command.aggregate
db.collection('students').aggregate()
  .group({
    _id: null,
    ageStdDev: $.stdDevSamp('$score')}).end(a)Copy the code

Results:

{ "_id": null."ageStdDev": 14.142135623730951 }
Copy the code

If you add a new record to the collection STUDENTS, its score field type is string:

{ "score": "aa" }
Copy the code

When calculating the standard sample bias using the above code, stdDevSamp automatically ignores records that are not of type number and returns the same result.

sum

Computes and returns the sum of all values of a set of fields.

API
db.command.aggregate.sum(<expression>)
Copy the code

An expression can pass in a specified field or a list of specified fields. Sum automatically ignores non-numeric values. If all values under the field are non-numbers, the result returns 0. If a numeric constant is passed in, it is treated as if all the values of the record field were given to the given constant and added up during aggregation, resulting in the number of input records multiplied by the constant.

The sample

The collection of goods is recorded as follows: price: sales amount of goods, cost: cost of goods

{ "cost": - 10."price": 100 }
{ "cost": - 15."price": 1 }
{ "cost": - 10."price": 10 }
Copy the code

Separate fields

With the help of sum, you can calculate the total sales of all goods with the code:

const $ = db.command.aggregate
db
  .collection('goods')
  .aggregate()
  .group({
    _id: null,
    totalPrice: $.sum('$price')}).end(a)Copy the code

The results of

{ "_id": null."totalPrice": 111 }
Copy the code

Field list

If we need to calculate the total profit of all goods, we need to add the cost and price of each item to get the profit of goods corresponding to this record. Then calculate the total profit.

With sum, the code is:

const $ = db.command.aggregate
db
  .collection('goods')
  .aggregate()
  .group({
    _id: null,
    totalProfit: $.sum($.sum(['$price'.'$cost'))}).end(a)Copy the code

Results:

{ "_id": null."totalProfit": 76 }
Copy the code