#
$abs(numberOrExpression) → {AbsOperator }
Returns the absolute value of a number.
Parameters:
Name
Type
Description
numberOrExpression
NumberExpression
A number or an expresison that
resolves to a number.
See:
View Source
index.ts , line 834
Example
$abs(-1);
// returns
{ $abs: -1 }
#
$acos(numberOrExpression) → {AcosOperator}
Returns the inverse cosine (arc cosine) of a value.
Parameters:
Name
Type
Description
numberOrExpression
NumberExpression
A number or an expression that
resolves to a number.
See:
View Source
index.ts , line 849
Example
$radiansToDegrees($acos($divide('$side_b', '$hypotenuse')));
// returns
{ $radiansToDegrees: { $acos: { $divide: ['$side_b', '$hypotenuse'] } } }
#
$acosh(numberOrExpression) → {AcoshOperator}
Returns the inverse hyperbolic cosine (hyperbolic arc cosine) of a value.
Parameters:
Name
Type
Description
numberOrExpression
NumberExpression
A number or an expression that
See:
View Source
index.ts , line 863
Example
$radiansToDegrees($acosh('$x'));
// returns
{ $radiansToDegrees: { $acosh: '$x' } }
#
$add(expression) → {AddOperator}
Adds numbers together or adds numbers and a date.
Parameters:
See:
View Source
index.ts , line 881
Examples
Addends as arguments
$add(1, 2, 3);
// returns
{ $add: [1, 2, 3] }
Addends as array
$add([1, 2, 3]);
// returns same as above
Adds new fields to documents.
Parameters:
Name
Type
Description
expression
ObjectExpression
Specify the name of each field to add
and set its value to an aggregation expression or an empty object.
See:
View Source
index.ts , line 115
Example
$addFields({ fullName: $.concat('$firstName', ' ', '$lastName') });
// returns
{ $addFields: { fullName: { $concat: ['$firstName', ' ', '$lastName'] } } }
#
$addSafe(…expression) → {AddOperator}
Add safetely, ensuring all expressions resolve a number. Null values resolve
to zero.
Parameters:
Name
Type
Attributes
Description
expression
NumberExpression
<repeatable>
Numbers or expressions to adds.
See:
To Do:
Protect from non-null & non-numeric values.
View Source
index.ts , line 902
Examples
Non literal numbers input
$addSafe(1, 2, '$myVar');
// returns
{ $add: [1, 2, { $ifNull: ['$myVar', 0] }] }
All literal numbers input
$addSafe(1, 2, 3);
// returns
{ $add: [1, 2, 3] }
#
$addToSet(expression) → {AddToSetOperator}
Returns an array of all unique values that results from applying an
expression to each document in a group.
Parameters:
Name
Type
Description
expression
Expression
A valid expression.
See:
View Source
index.ts , line 917
Example
$addToSet('$item');
// returns
{ $addToSet: '$item' }
#
$all(…expressions) → {AllOperator}
Selects documents where the value of a field is an array that contains all
the specified elements.
Parameters:
Name
Type
Attributes
Description
expressions
Array.<Expression >
<repeatable>
Match expression.
View Source
index.ts , line 926
Returns:
The compiled $all operator.
Type:
AllOperator
#
$allElementsTrue(…expressions) → {AllElementsTrueOperator}
Evaluates an array as a set and returns `true` if no element in the array is
`false`. Otherwise, returns false. An empty array returns `true`.
Parameters:
Name
Type
Attributes
Description
expressions
Expression
<repeatable>
Any valid expressions.
See:
View Source
index.ts , line 941
Returns:
Type:
AllElementsTrueOperator
Example
$allElementsTrue('$a', '$b', ['$c', '$d']);
// returns
{ $allElementsTrue: ['$a', '$b', ['$c', '$d']] }
#
$and(…expressions) → {AndOperator}
Evaluates one or more expressions and returns true if _all_ of the
expressions are `true` or if run with no argument expressions.
Parameters:
Name
Type
Attributes
Description
expressions
Expression
<repeatable>
Any valid expressions.
See:
View Source
index.ts , line 959
Examples
$and($or('$a', '$b'), '$c');
// returns
{ $and: [{ $or: ['$a', '$b'], '$c'] }
First argument array
$and([$or('$a', '$b'), '$c']);
// returns same as above
#
$anyElementTrue(…expressions) → {AnyElementTrueOperator}
Evaluates an array as a set and returns `true` if any of the elements are
`true`. Returns `false` otherwise.
Parameters:
Name
Type
Attributes
Description
expressions
Expression
<repeatable>
Any valid expressions.
See:
View Source
index.ts , line 974
Returns:
Type:
AnyElementTrueOperator
Example
$anyElementsTrue('$a', '$b', ['$c', '$d']);
// returns
{ $anyElementsTrue: ['$a', '$b', ['$c', '$d']] }
#
$arrayElemAt(arrayExpression, index) → {ArrayElemAtOperator}
Returns the element at the specified array index.
Parameters:
Name
Type
Description
arrayExpression
ArrayExpression
An array or a valid expression that
resolves to an array.
index
NumberExpression
A number of any valid expression that
resolves to a number.
See:
View Source
index.ts , line 991
Returns:
Type:
ArrayElemAtOperator
Example
$arrayElemAt('$favorites', 0);
// returns
{ $arrayElemAt: ['$favorites', 0] }
#
$arrayElemFirst(inputArray) → {ArrayElemAtOperator}
Returns the first element in an array.
Parameters:
Name
Type
Description
inputArray
ArrayExpression
An arra or a valid expression that
resolves to an array.
View Source
index.ts , line 1005
Returns:
Returns an $arrayElemAt operator with 0 as the
idx parameter.
Type:
ArrayElemAtOperator
Example
$arrayElemFirst('$myArray')
// returns
{ $let: { vars: { inputArray: '$myArray' }, in: { $arrayElemAt: ['$myArray', 0] } } }
#
$arrayElemLast(inputArray) → {ArrayElemAtOperator}
Returns the last element in an array.
Parameters:
Name
Type
Description
inputArray
ArrayExpression
An arra or a valid expression that
resolves to an array.
View Source
index.ts , line 1025
Returns:
Returns an $arrayElemAt operator with the idx
parameter calculated from the size of the array for the last element.
Type:
ArrayElemAtOperator
Example
$arrayElemLast('$myArray')
// returns
{ $let: {
vars: { inputArray: '$myArray' },
in: { $let: {
vars: { length: { $size: '$$inputArray' } },
in: { $arrayElemAt: ['$$inputArray', { $subtract: ['$$length', -1] } },
} },
} }
#
$arrayToObject(arrayInput) → {ArrayToObjectOperator}
Converts an array into a single document.
Parameters:
Name
Type
Description
arrayInput
ArrayToObjectExpression
An array of two-element arrays
where the first element is the field name, and the second element is the
field value OR An array of documents that contains two fields, k and v where
k contains the field name and v contains the value of the field.
See:
View Source
index.ts , line 1049
Returns:
Returns an $arrayToObject operator populated
based on input.
Type:
ArrayToObjectOperator
Examples
Key-value object
$arrayToObject([
{ k: 'item', v: 'abc123' },
{ k: 'qty', v: '$qty' },
]);
Key-value pair
$arrayToObject([
['item', 'abc123'],
['qty', '$qty'],
]);
#
$asin(numberExpression) → {AsinOperator}
Returns the inverse sine (arc sine) of a value.
Parameters:
Name
Type
Description
numberExpression
NumberExpression
Any valid expression that resolves
to a number between -1 and 1.
See:
View Source
index.ts , line 1064
Example
$asin($divide('$side_a', '$hyoptenuse'));
// returns
{ $asin: { $divide: ['$side_a', '$hypotenuse'] } }
#
$asinh(numberExpression) → {AsinhOperator}
Returns the inverse hyperbolic sine (hyperbolic arc sine) of a value.
Parameters:
Name
Type
Description
numberExpression
NumberExpression
Any valid expression that resolves
to a number.
See:
View Source
index.ts , line 1079
Example
$asinh('$x-coordinate');
// returns
{ $asinh: '$x-coordinate' }
#
$atan(numberExpression) → {AtanOperator}
Returns the inverse tangent (arc tangent) of a value.
Parameters:
Name
Type
Description
numberExpression
NumberExpression
Any valid expression that resolves
to a number.
See:
View Source
index.ts , line 1094
Example
$atan($divide('$side_b', '$side_a'));
// returns
{ $atan: { $divide: ['$side_b', '$side_a'] } }
#
$atanh(numberExpression) → {AtanhOperator}
Returns the inverse hyperbolic tangent (hyperbolic arc tangent) of a value.
Parameters:
Name
Type
Description
numberExpression
NumberExpression
Any valid expression that resolves
to a number between -1 and 1.
See:
View Source
index.ts , line 1109
Example
$atanh('$x-coordinate');
// returns
{ $atanh: '$x-coordinate' }
#
$avg(expression) → {AverageOperator}
Returns the average value of the numeric values ignoring non-numeric values.
Parameters:
Name
Type
Description
expression
AverageExpression
Varies based on the stage it is being
used in. See documentation.
See:
View Source
index.ts , line 1124
Example
$avg('$quantity');
// returns
{ $avg: '$quantity' }
#
$binarySize(mixedInput) → {BinarySizeOperator}
Returns the size of a given string or binary data value's content in bytes.
Parameters:
Name
Type
Description
mixedInput
string
|
Binary
|
null
Refer to documentation for
details.
See:
View Source
index.ts , line 1139
Example
$binarySize('$binary');
// returns
{ $binarySize: '$binary' }
#
$bitAnd(…expressions)
Returns the result of a bitwise and operation on an array of int or long
values.
Parameters:
Name
Type
Attributes
Description
expressions
ObjectExpression
<repeatable>
int or long values.
See:
View Source
index.ts , line 1153
Example
$bitAnd('$myInt', '$myLong');
// returns
{ $bitAnd: ['$myInt', '$myLong'] }
#
$bitNot(…expressions)
Returns the result of a bitwise not operation on a single int or long value.
Parameters:
Name
Type
Attributes
Description
expressions
ObjectExpression
<repeatable>
int or long values.
See:
View Source
index.ts , line 1166
Example
$bitNot('$x');
// returns
{ $bitNot: '$x' }
#
$bitOr(…expressions)
Returns the result of a bitwise or operation on an array of int and long
values.
Parameters:
Name
Type
Attributes
Description
expressions
ObjectExpression
<repeatable>
int or long values.
See:
View Source
index.ts , line 1180
Example
$bitOr('$myInt', '$myLong');
// returns
{ $bitOr: ['$myInt', '$myLong'] }
#
$bitXor(…expressions)
Returns the result of a bitwise xor operation on an array of int and long
values.
Parameters:
Name
Type
Attributes
Description
expressions
ObjectExpression
<repeatable>
int or long values.
See:
View Source
index.ts , line 1194
Example
$bitXor('$myInt', '$myLong');
// returns
{ $bitXor: ['$myInt', '$myLong'] }
#
$bsonSize(expression) → {BsonSizeOperator}
Returns the size in bytes of a given document when encoded as BSON.
Parameters:
Name
Type
Description
expression
ObjectExpression
|
null
Any valid expression that
resolves an object or null.
See:
View Source
index.ts , line 1209
Example
$bsonSize('$$ROOT');
// returns
{ $bsonSize: '$$ROOT' }
#
$bucket(groupBy, boundariesopt , defaultIdopt , output) → {Bucket}
Categorizes incoming documents into groups called buckets, based on a
specified expression and bucket boundaries.
Parameters:
Name
Type
Attributes
Description
groupBy
Expression
An expression to group documents by.
boundaries
Array.<number>
<optional>
An array of values based on the groupBy
expression that specify the boundaries for each bucket.
defaultId
Expression
<optional>
Optional. A literal that specifies the _id of
an additional bucket that contains all documents that don't fall into a
bucket specified by boundaries.
output
ObjectExpression
Optional. A document that specifies the
fields to include.
See:
View Source
index.ts , line 176
Returns:
A Bucket object populated according to argument input.
Type:
Bucket
Examples
Static notation
$bucket('$price', [0, 200, 400], 'Other');
// outputs
{ $bucket: { groupBy: '$price', boundaries: [0, 200, 400], default: 'Other' } }
Object notation
$bucket('$price').boundaries(0, 200, 400).default('Other');
// outputs
{ $bucket: { groupBy: '$price', boundaries: [0, 200, 400], default: 'Other' } }
#
$bucketAuto(groupBy, bucketsopt , granularityopt , outputopt ) → {Bucket}
Categorizes incoming documents into a specific number of groups, called
buckets, based on a specified expression.
Parameters:
Name
Type
Attributes
Description
groupBy
Expression
An expression to group documents by.
buckets
number
<optional>
A positive number for the number of buckets into
which input documents will be grouped.
expression that specify the boundaries for each bucket.
granularity
string
<optional>
Optional. Specifies the preferred number series
to use.
output
ObjectExpression
<optional>
Optional. A document that specifies the
fields to include.
See:
View Source
index.ts , line 237
Returns:
A Bucket object populated according to argument input.
Type:
Bucket
Examples
Static notation
$bucketAuto('$_id', 5);
// returns
{ $bucketAuto: { groupBy: '$_id', buckets: 5 } }
Object notation
$bucketAuto('$_id').buckets(5).granularity('R5');
// returns
{ $bucketAuto: { groupBy: '$_id', buckets: 5, granularity: 'R5' } }
#
$ceil(numberExpression) → {CeilOperator}
Returns the smallest integer greater than or equal to the specified number.
Parameters:
Name
Type
Description
numberExpression
NumberExpression
Any valid expression that resolves
to a number.
See:
View Source
index.ts , line 1224
Example
$ceil('$value');
// returns
{ $ceil: '$value' }
#
$changeStream(optsopt ) → {ChangeStream}
Returns a Change Stream cursor on a collection, a database, or an entire
cluster. Must be the first stage in the pipeline.
Parameters:
Name
Type
Attributes
Description
opts
ChangeStreamExpression
<optional>
Change stream options.
See:
View Source
index.ts , line 322
Returns:
A ChangeStream instance populated according to
argument input.
Type:
ChangeStream
Example
Basic example
$changeStream();
// returns
{ $changeStream: {} }
#
$cmp(expression1, expression2) → {CmpOperator}
Compares two values.
Parameters:
Name
Type
Description
expression1
Expression
Any valid expression.
expression2
Expression
Any valid expression.
See:
View Source
index.ts , line 1246
Example
$cmp('$qty', 250);
// returns
{ $cmp: ['$qty', 250] }
#
$concat(…stringParts) → {ConcatOperator}
Concatenates strings returning the result.
Parameters:
Name
Type
Attributes
Description
stringParts
StringExpression
<repeatable>
The string parts to concatenate.
See:
View Source
index.ts , line 1263
Examples
String parts as arguments
$concat('$item', ' - ', '$description');
// returns
{ $concat: ['$item', ' - ', '$description'] }
First argument array
$concat(['$item', ' - ', '$description']);
// returns same as above
#
$concatArrays(…arrays) → {ConcatArraysOperator}
Concatenates arrays.
Parameters:
Name
Type
Attributes
Description
arrays
ArrayExpression
<repeatable>
The arrays to concatenate.
See:
View Source
index.ts , line 1300
Returns:
Type:
ConcatArraysOperator
Example
$concatArrays('$myArray', [1, 2]);
// returns
{ $concatArrays: ['$myArray', [1, 2]] }
#
$concatArraysSafe(…args) → {ConcatArraysOperator}
Safely concatenate arrays.
Parameters:
Name
Type
Attributes
Description
args
ArrayExpression
<repeatable>
The arrays to concatenate.
See:
View Source
index.ts , line 1314
Returns:
Returns a $concatArrays operator with each
operand ensured to be an array.
Type:
ConcatArraysOperator
Example
$concatArraySafe([1, 2, 3], [4, 5], '$c')
// returns
{ $concatArrays: [[1, 2, 3], [4, 5], { $cond: { if: { $isArray: '$c' }, then: '$c', else: [] } }] }
#
$concatSafe(…args) → {ConcatOperator}
Safely concatenates values as strings returning the result.
Parameters:
Name
Type
Attributes
Description
args
Expression
|
Array.<Expression >
<repeatable>
The parts to concatenate.
See:
View Source
index.ts , line 1281
Returns:
A $concat operator with each operand ensured to
return a string.
Type:
ConcatOperator
Examples
String parts as arguments
$concatSafe('$item', ' - ', '$description');
// wraps each non-literal string with $ensureString
{ $concat: [$ensureString('$item'), ' - ', $ensureString('$description')] }
First argument array
$concatSafe(['$item', ' - ', '$description']);
// returns same as above
#
$cond(ifExpr, thenExpropt , elseExpropt ) → {Condition}
Evaluates a boolean expression to return one of the two specified return
expressions.
Parameters:
Name
Type
Attributes
Description
ifExpr
Expression
A boolean expression.
thenExpr
Expression
<optional>
The true case.
elseExpr
Expression
<optional>
The false case.
See:
View Source
index.ts , line 1355
Returns:
Returns a "Condition" object that represents the $cond
operator whose usage varies based on the optional arguments (`thenExpr`
and `elseExpr`).
_The optional arguments are required but can be alternatively be provided
using a corresponding method (see the Object Notation example).
Type:
Condition
Examples
Static Notation
$cond($.lte($.size('$myArray'), 5), '$myArray', $.slice('$myArray', -5));
Object Notation
$cond($.lte($.size('$myArray'), 5)).then('$myArray').else($.slice('$myArray', -5));
#
$convert(value, toType, defaultValue) → {ConvertOperator}
Converts a value to a specified type.
Parameters:
Name
Type
Description
value
Expression
The value to convert. Can be any valid expression.
toType
ConversionTypeExpression
The
defaultValue
Expression
The result if the value to convert is null
or induces an error.
See:
View Source
index.ts , line 1419
Returns:
A $convert operator object populated based on
input with additional methods for advanced usage.
Type:
ConvertOperator
Examples
Static notation
$convert('$myValue', 'int');
// returns
{ $convert: { input: '$myValue', to: 'int' } }
Object notation
$convert('$myValue', 'int').onError(-1).onNull(0);
// returns
{ $convert: { input: '$myValue', to: 'int', onError: -1, onNull: 0 } }
#
$cos(numberExpression) → {CosOperator}
Returns the cosine of a value that is measured in radians.
Parameters:
Name
Type
Description
numberExpression
NumberExpression
Any valid expression that resolves
to a number.
See:
View Source
index.ts , line 1434
Example
$cos($degreesToRadians('$angle_a'));
// returns
{ $cos: { $degreesToRadians: '$angle_a' } }
#
$cosh(numberExpression) → {CoshOperator}
Returns the hyperbolic cosine of a value that is measured in radians.
Parameters:
Name
Type
Description
numberExpression
NumberExpression
Any valid expression that resolves
to a number.
See:
View Source
index.ts , line 1449
Example
$cosh($degreesToRadians('$angle'));
// returns
{ $cosh: { $degreesToRadians: '$angle' } }
#
$count(nameopt ) → {CountOperator}
Passes a document to the next stage that contains a count of the number of
documents input to the stage.
Parameters:
Name
Type
Attributes
Default
Description
name
string
<optional>
count
The name of the output field for the count value.
Must be a non-empty string, must not start with `$` nor contain `.`.
See:
View Source
index.ts , line 342
Returns:
A $count operator expression.
Type:
CountOperator
Examples
$count('myCount');
// returns
{ $count: 'myCount' }
Use default name "count"
$count();
// returns
{ $count: "count" }
#
$covariancePop(expression1, expression2) → {CovariancePopOperator}
Returns the population covariance of two numeric expressions that are
evaluated using documents in the $setWindowFields stage window.
Parameters:
Name
Type
Description
expression1
NumberExpression
A number of any valid expression that
resolves to a number.
expression2
NumberExpression
A number of any valid expression that
resolves to a number.
See:
View Source
index.ts , line 1467
Returns:
Type:
CovariancePopOperator
Example
$covariancePop($year('$orderDate'), '$quantity');
// returns
{ $covariancePop: [{ $year: '$orderDate' }, '$quantity'] }
#
$covarianceSamp(expression1, expression2) → {CovarianceSampOperator}
Returns the sample covariance of two numeric expressions that are evaluated
using documents in the $setWindowFields stage window.
Non-numeric, null and missing fields are ignored.
Parameters:
Name
Type
Description
expression1
NumberExpression
A number of any valid expression that
resolves to a number.
expression2
NumberExpression
A number of any valid expression that
resolves to a number.
See:
View Source
index.ts , line 1486
Returns:
Type:
CovarianceSampOperator
Example
$covarianceSamp($year('$orderDate'), '$quantity');
// returns
{ $covarianceSamp: [{ $year: '$orderDate' }, '$quantity'] }
#
$decrement(value) → {SubtractOperator}
Decrement a number by 1.
Parameters:
Name
Type
Description
value
NumberExpression
A number of any valid expression that
resolves to a number.
View Source
index.ts , line 1499
Returns:
A $subtract operator with `1` fixed as the
subtrahend.
Type:
SubtractOperator
Example
$decrement('$x')
// returns
{ $subtract: ['$x', 1] }
#
$degreesToRadians(numberExpression) → {DegreesToRadiansOperator}
Converts the input value measured in degrees to radians.
Parameters:
Name
Type
Description
numberExpression
NumberExpression
Any valid expression that resolves
to a number.
See:
View Source
index.ts , line 1514
Returns:
Type:
DegreesToRadiansOperator
Example
$degreesToRadians('$angle_a');
// returns
{ $degreesToRadians: '$angle_a' }
#
$divide(dividend, divisor) → {DivideOperator}
Divides one number by another and returns the result.
Parameters:
Name
Type
Description
dividend
NumberExpression
A number of any valid expression that
resolves to a number.
divisor
NumberExpression
A number of any valid expression that
resolves to a number.
See:
View Source
index.ts , line 1532
Example
$divide(9, 3);
// returns
{ $divide: [9, 3 }
#
$divideSafe(dividend, divisor, defaultValueopt ) → {DivideOperator}
Safely divide one number by another. Division by zero will return the
`defaultValue`.
Parameters:
Name
Type
Attributes
Default
Description
dividend
NumberExpression
|
null
|
undefined
A number or any expression that resolves
to a number.
divisor
NumberExpression
|
null
|
undefined
A number or any expression that resolves
to a number.
defaultValue
NumberExpression
<optional>
$$REMOVE
The default value if the division
operation cannot be performed.
View Source
index.ts , line 1566
Returns:
A $divide operator populated according to argument
input.
Type:
DivideOperator
Examples
$divideSafe('$a', '$b');
// returns
{ $let: {
vars: {
dividend: { $ifNull: ['$a', 0] },
divisor: { $ifNull: ['$b', 0] },
},
in: { $cond: {
if: { $eq: ['$$divisor', 0] },
then: 0,
else: { $divide: ['$dividend', '$divisor'] },
} },
} }
Literal input
$divideSafe(9, 3); // returns { $divide: [9, 3] }
$divideSafe(true, 3); // returns 0
$divideSafe(9, false); // returns 0
$divideSafe(9, null); // returns 0
$divideSafe(null, 3); // returns 0
#
$documentNumber() → {DocumentNumberOperator}
Returns the position of a document in the $setWindowFields stage.
See:
View Source
index.ts , line 1616
Returns:
Type:
DocumentNumberOperator
Example
$documentNumber();
// returns
{ $documentNumber: {} }
#
$documents(mixed, …argsopt ) → {DocumentsStage}
Returns literal documents from input values.
Parameters:
Name
Type
Attributes
Description
mixed
ObjectExpression
|
Array.<ObjectExpression>
The first document
or an array of documents.
args
Array.<ObjectExpression>
<optional>
<repeatable>
Additional documents to input into the
pipeline.
See:
View Source
index.ts , line 359
Returns:
Returns a $document operator based on input.
Type:
DocumentsStage
Example
$documents({ x: 10 }, { x: 2 }, { x: 5 });
// returns
{ $documents: [{ x: 10 }, { x: 2 }, { x: 5 }
#
$each(expression) → {EachOperator}
Query operator. Not known to work in aggregations.
Parameters:
Name
Type
Description
expression
ArrayExpression
A valid expression that resolves to an array.
Deprecated: Unless new information is discovered.
View Source
index.ts , line 1625
Returns:
Operator with the expression embedded.
Type:
EachOperator
#
$elemMatch(query) → {ElemMatchOperator}
Matches documents that contain an array field with at least one elements
matching the query criteria.
Parameters:
Name
Type
Description
query
ObjectExpression
A valid expression that resolves to an array.
Deprecated: Unless new information is discovered.
View Source
index.ts , line 1635
Returns:
Operator with the expression embedded.
Type:
ElemMatchOperator
#
$ensureArray(value) → {Array.<any>|Condition}
Ensure an expression resolves an array. Non-array values return an empty
array.
Parameters:
Name
Type
Description
value
Expression
|
null
|
undefined
The value to ensure is an array.
View Source
index.ts , line 1660
Returns:
Returns a literal array for invalid literal
input and a Condition for variable input.
Type:
Array.<any>
|
Condition
Examples
$ensureArray('$myVar');
// returns
{ $let: {
vars: { input: '$myVar' },
in: { $cond: { if: { $isArray: '$$input' }, then: '$$input', else: [] } },
} }
Literal input
$ensureArray([1, 2, 3]); // returns [1, 2 3]
$ensureArray('myString'); // returns [];
$ensureArray(1); // returns [];
$ensureArray(true); // returns [];
$ensureArray(false); // returns [];
$ensureArray(undefined); // returns [];
$ensureArray(null); // returns [];
#
$ensureNumber(value, defaultValueopt ) → {number|Condition}
Ensure an expression resolves a number.
Parameters:
Name
Type
Attributes
Default
Description
value
Expression
|
null
|
undefined
The value to ensure is a number.
is null or induces an error.
defaultValue
NumberExpression
<optional>
0
The value to return for null
values or when converting the input value to a double produces an error.
View Source
index.ts , line 1703
Returns:
Returns a number of a $cond expression that
will convert non-numeric types to a double.
Type:
number
|
Condition
Examples
$ensureNumber('$myVar');
// returns
{ $cond: {
if: { $in: [{ $type: '$myVar' }, ['decimal', 'int', 'double', 'long'] },
then: '$myVar',
else: { $convert: { input: '$myVar', to: 1, onError: 0, onNull: 0 },
} }
Literal input
$ensureNumber(123); // returns 123
$ensureNumber(true); // returns 1
$ensureNumber(false); // returns 0
#
$ensureString(value, defaultValueopt ) → {string|ConvertOperator}
Ensure an expression resolves a string.
Parameters:
Name
Type
Attributes
Description
value
Expression
|
null
|
undefined
The value to ensure is of the specified type.
defaultValue
StringExpression
<optional>
Override the default value of ""
if the conversion results in null or induces an error.
See:
View Source
index.ts , line 1744
Returns:
A literal string if the input value is a
literal string. Otherwise a ConvertOperator populated accordinly is returned.
Type:
string
|
ConvertOperator
Examples
$ensureString('$myVariable');
// returns
{ $convert: { input: '$myVariable', to: 2, onError: '', onNull: '' } },
Literal string input
$ensureString('literalString');
Literal number input
$ensureString(1); // returns "1"
$ensureString(1.1); // returns "1.1"
Literal boolean input
$ensureString(true); // returns ""
$ensureString(false); // return ""
#
$eq(expression1, expression2) → {EqOperator}
Compares two values and returns `true` when the values are equivalent and
`false` otherwise.
Parameters:
Name
Type
Description
expression1
Expression
First expression.
expression2
Expression
Second expression.
See:
View Source
index.ts , line 1779
Example
$eq('$qty', 250);
// returns
{ $eq: ['$qty', 250] }
#
$exp(numberExpression) → {ExpOperator}
Raises Euler's number to the specified exponent and returns the result.
Parameters:
Name
Type
Description
numberExpression
NumberExpression
Any valid expression that resolves
to a number.
See:
View Source
index.ts , line 1801
Example
$exp('$interestRate');
// returns
{ $exp: '$interestRate' }
#
$expr(expression) → {ExprOperator}
Allows the use of some aggregation operators otherwise unavailable to the
aggregation stage.
Parameters:
Name
Type
Description
expression
Expression
Any valid aggregation expression.
View Source
index.ts , line 1810
Returns:
The compiled $expr expression.
Type:
ExprOperator
#
$facet(expression) → {FacetStage}
Processes multiple aggregation pipelines within a single stage on the same
set of input documents.
Parameters:
Name
Type
Description
expression
FacetExpression
Refer to documentation.
See:
View Source
index.ts , line 383
Example
$project({ x: '$y' });
// returns
{ $project: { x: '$y' } }
#
$filter(inputExpr, asNameopt , condExpropt , limitopt ) → {FilterOperator}
Filters an array based on the specified condition returning the items that
match the condition.
Parameters:
Name
Type
Attributes
Description
inputExpr
ArrayExpression
An expression that resolves to an array.
asName
string
<optional>
Optional. A name for the value that represents each
element of the input array. If no name is specified, the variable name
defaults to `this`.
condExpr
Expression
<optional>
An expression that resolves to boolean and can
references each elements of the input array with the variable name specified
in as().
limit
number
<optional>
Optional. A number expression that restricts the
number of matching array elements to return.
See:
View Source
index.ts , line 1863
Returns:
A FilterOperator
Type:
FilterOperator
Examples
Static notation
$filter('$myArray', 'item', '$$item.sold', 10);
// returns
{ $filter: { input: '$myArray', as: 'item', cond: '$$item.sold', limit: 10 } }
Object notation
$filter('$myArray').as('item').cond('$$item.sold').limit(10);
// returns same as above
#
$first(expression) → {FirstOperator}
Returns the result of an expression for the first document in a group of
documents.
Parameters:
Name
Type
Description
expression
Expression
Expression that resolves a value from the
document.
See:
View Source
index.ts , line 1880
Example
$first('$date');
// returns
{ $first: '$date' }
#
$floor(numberExpression) → {FloorOperator}
Returns the largest integer less than or equal to the specified number.
Parameters:
Name
Type
Description
numberExpression
NumberExpression
Any valid expression that resolves
to a number.
See:
View Source
index.ts , line 1895
Example
$floor('$value');
// returns
{ $floor: '$value' }
#
$group(expression) → {GroupStage}
Separates documents into groups according to a "group key".
Parameters:
Name
Type
Description
expression
ObjectExpression
Refer to documentation.
See:
View Source
index.ts , line 397
Example
$group({ _id: '$userId', total: $sum(1)) });
// returns
{ $group: { _id: '$userId', total: { $sum: 1 } } };
#
$if(ifExpr) → {Condition}
Shortcut object-notation for the $cond operation (if/then/else).
Parameters:
Name
Type
Description
ifExpr
Expression
A boolean expression.
See:
View Source
index.ts , line 1915
Returns:
A Condition object that resembles the $cond operation
whose then and else case should be set using the corresponding methods.
Type:
Condition
Example
$if($.lte($.size('$myArray'), 5), '$myArray', $.slice('$myArray', -5));
#
$ifNull(input, replacement) → {IfNullOperator}
Evaluates input expressions for null values and returns the first non-null
value.
TODO - Should support more than two args.
Parameters:
See:
View Source
index.ts , line 1932
Example
$ifNull('$myArray', []);
// returns
{ $ifNull: ['$myArray', []] }
#
$increment(value) → {AddOperator}
Increment a number by 1.
Parameters:
Name
Type
Description
value
NumberExpression
A number or any valid expression that
resolves to a number.
View Source
index.ts , line 1944
Returns:
An $add operator with a fixed added of 1.
Type:
AddOperator
Example
$increment('$x')
// returns
{ $add: ['$x', 1] }
#
$isArray(expression) → {IsArrayOperator}
Determines if the operand is an array.
Parameters:
Name
Type
Description
expression
Expression
Any valid expression.
See:
View Source
index.ts , line 1969
Example
$isArray('$value');
// returns
{ $isArray: '$value' }
#
$isNumber(expression) → {IsNumberOperator}
Checks if the specified expression resolves to a numeric BSON type.
Parameters:
Name
Type
Description
expression
Expression
Any valid expression.
See:
View Source
index.ts , line 1983
Example
$isNumber('$value');
// returns
{ $isNumber: '$value' }
#
$last(expression) → {LastOperator}
Returns the result of an expression of the last document in a group of
documents. Only meaningful when documents are in a defined order.
Parameters:
Name
Type
Description
expression
Expression
Any valid expression.
See:
View Source
index.ts , line 1998
Example
$last('$myArr');
// return
{ $last: '$myArray' }
#
$let(varsExpr, inExpropt ) → {LetVarsIn}
Binds variables for use in the specified expression and returns the result of
the expression.
Parameters:
Name
Type
Attributes
Description
varsExpr
Expression
Assign for the variables accessible in the in
expression.
inExpr
Expression
<optional>
The expression to evaluate.
See:
View Source
index.ts , line 2042
Returns:
Returns a "LetVarsIn" object that resembles the $let
operator whose usage varies based on the optional arguments.
_The optional arguments can be alternatively be provided using a
corresponding method (see the Object Notation example).
Type:
LetVarsIn
Examples
Static Notation
$let({ myVar: 'val' }, $.concat('myVar equals: ', '$$myVar'));
Object Notation #1
$let({ myVar: 'val' }}).in($.concat('myVar equals: ', '$$myVar'));
Object Notation #2
$let().vars({ myVar: 'val' }}).in($.concat('myVar equals: ', '$$myVar'));
Return value of all above examples
{ $let: { vars: { myVar: 'val', in: { $concat: ['myVar equals: ', '$$myVar'] } } } }
#
$limit(value) → {LimitStage}
Limits the number of documents passed to the next stage in the pipeline.
Parameters:
Name
Type
Description
value
number
A positive 64bit integer.
See:
View Source
index.ts , line 411
Example
$limit(10);
// returns
{ $limit: 10 }
#
$linearFill(expression) → {LinearFillOperator}
Fills null and missing fields in a window using linear interpolation based on
surrounding field values.
Only available in the $setWindowFields stage.
Parameters:
Name
Type
Description
expression
Expression
A valid expression.
See:
View Source
index.ts , line 2058
Example
$linearFill('$price');
// returns
{ $linearFill: '$price' }
#
$literal(value) → {LiteralOperator}
Returns a value without parsing. Use for values that the aggregation pipeline
may interpret as an expression.
Parameters:
Name
Type
Description
value
any
Any value
See:
View Source
index.ts , line 2073
Example
$literal(1);
// returns
{ $literal: 1 }
#
$locf(expression) → {LocfOperator}
Last observation carried forward. Sets values for null and missing fields in
a window to the last non-null value for the field.
Only available in the $setWindowFields stage.
Parameters:
Name
Type
Description
expression
Expression
A valid expression.
See:
View Source
index.ts , line 2089
Example
$locf('$price');
// returns
{ $locf: '$price' }
#
$log(expression1, expression2) → {LogOperator}
Calculates the log of a number in the specified base and returns the result
as a double.
Parameters:
Name
Type
Description
expression1
NumberExpression
A number of any valid expression that
resolves to a non-negative number.
expression2
NumberExpression
A number of any valid expression that
resolves to a positive number greater than 1.
See:
View Source
index.ts , line 2107
Example
$log('$int', 2);
// returns
{ $log: ['$int', 2] }
#
$log10(numberOrExpression) → {Log10Operator}
Calculates the log base 10 of a number and returns the result as a double.
Parameters:
Name
Type
Description
numberOrExpression
NumberExpression
A number or an expresison that
resolves to a number.
See:
View Source
index.ts , line 2122
Example
$log10('$H30');
// returns
{ $log10: '$H30' }
#
$lookup(from, asNameopt , localFieldopt , foreignFieldopt ) → {Lookup}
Performs a left outer join to a collection in the same database adding a new
array field to each input document.
Parameters:
Name
Type
Attributes
Description
from
MixedCollectionName
|
Array.<ObjectExpression>
Specifies the collection in the same
database to perform the join with. Can be either the collection name or the
Collection object.
asName
string
<optional>
Specifies the name of the new array field to add to
the input documents where the results of the lookup will be.
localField
string
<optional>
Specifies the field from the documents input to
the lookup stage.
foreignField
string
<optional>
Specifies the field in the from collection the documents input to
the lookup stage.
View Source
index.ts , line 507
Returns:
A Lookup instance populated based on argument input that
contains the relevant methods for otherwise configuring a $lookup stage.
Type:
Lookup
Examples
Common lookup
$lookup('myCollection', 'myVar', 'localId', 'foreignId');
// returns a Lookup object populated like:
{ $lookup: { from: 'myCollection', as: 'myVar', localField: 'localId', foreignField: 'foreignId' } }
Lookup with $documents in pipeline
// Pass the documents as an array using the "from" argument
$lookup([{ k: 1 }, { k: 2 }], 'subdocs')
.let({ key: '$docKey' })
.pipeline($.match({ k: '$$key' }));
// returns a Lookup object populated as follows:
{
$lookup: {
as: 'subdocs',
let: { localField: '$docKey' },
pipeline: [
{ $documents: [{ k: 1 }, { k: 2 }] },
{ $match: { k: '$$localField' } },
],
},
}
#
$map(inputExpr, asNameopt , inExpropt ) → {MapOperator}
Applies an expression to each item in an array and returns an array with the
results.
Parameters:
Name
Type
Attributes
Description
inputExpr
ArrayExpression
An expression that resolves to an array.
asName
string
<optional>
A name for the variable that represents each
individual element of the input array.
inExpr
Expression
<optional>
An expression that is applied to each element of
the input array.
See:
View Source
index.ts , line 2169
Returns:
A MapOperator object populated based on input.
Type:
MapOperator
Example
Static notation
$map('$myArray', 'item', '$$item.name');
// returns
{ $map: { input: '$myArray', as: 'item', in: '$$item.name' } }
#
$match(fieldExpression) → {MatchStage}
Filters the documents to pass only the documents that match the specified
conditions(s) to the next pipeline stage.
Parameters:
Name
Type
Description
fieldExpression
ObjectExpression
See:
View Source
index.ts , line 522
Example
$match({ x: 1 });
// returns
{ $match: { x: 1 } },
#
$merge(into, onExpropt ) → {Merge}
Writes the results of the pipeline to a specified location. Must be the last
stage in the pipeline.
Parameters:
Name
Type
Attributes
Description
into
MixedCollectionName
|
DatabaseAndCollectionName
The collectionName or Collection object to
merge into.
onExpr
string
|
Array.<string>
<optional>
Field or fields that act as a unique
identifier for the document.
See:
To Do:
Add support for accepting a pipleine for whenMatched.
View Source
index.ts , line 601
Returns:
Returns a Merge object populated according to the provided
arguments.
Type:
Merge
Examples
On single-field
$merge('myCollection', 'key');
// returns
{ $merge: { into: 'myCollection', on: 'key' } }
On multiple fields
$merge('myCollection', ['key1', 'key2']);
{ $merge: { into: 'myCollection', on: ['key1', 'key2'] } }
Full example
$merge('myCollection', ['key1', 'key2'])
.whenMatched('replace')
.whenNotMatched('discard');
Returns the metadata associated with a document when performing a search.
Parameters:
Name
Type
Description
metaDataKeyword
MetaDataKeyword
See:
View Source
index.ts , line 2192
Example
$meta('textScore');
// returns
{ $meta: 'textScore' }
#
$mod(expression1, expression2) → {ModOperator}
Divides one number by another and returns the remainder.
Parameters:
Name
Type
Description
expression1
NumberExpression
A number of any valid expression that
resolves to a number.
expression2
NumberExpression
A number of any valid expression that
resolves to a number.
See:
View Source
index.ts , line 2211
Example
$mod('$hours', '$tasks');
// returns
{ $mod: ['$hours', '$tasks'] }
#
$multiply(…expressions) → {MultiplyOperator}
Multiplies numbers together and returns the result.
Parameters:
Name
Type
Attributes
Description
expressions
NumberExpression
<repeatable>
Any valid expression that resolves
to a number.
See:
View Source
index.ts , line 2226
Example
$multiply(1, 2, 3, 4);
// returns
{ $multiply: [1, 2, 3, 4] }
#
$multiplySafe(…expressions) → {MultiplyOperator}
Safely multiply numbers together.
Parameters:
Name
Type
Attributes
Description
expressions
NumberExpression
<repeatable>
Any valid expression that resolves
to a number.
See:
View Source
index.ts , line 2246
Examples
$multiplySafe('$a', 2, '$c');
// returns
{ $multiply: [{ $ifNull: ['$a', 0] }, 2, { $ifNull: ['$c', 0] } }
Literal input
$multiplySafe(1, 2, 3, 4); // returns { $multiply: [1, 2, 3, 4] }
$multiplySafe(1, true); // returns 0;
$multiplySafe(false, 2); // returns 0;
$multiplySafe(null, 2); // returns 0;
$multiplySafe(1, undefined); // returns 0;
#
$ne(expression1, expression2) → {NeOperator}
Compares two values and returns true when the values are not equivalent and
false when the values are equivalent.
Parameters:
Name
Type
Description
expression1
Expression
Any valid expression.
expression2
Expression
Any valid expression.
See:
View Source
index.ts , line 2262
Example
$ne('$qty', 250);
// returns
{ $ne: ['$qty', 250] }
#
$nor(expression) → {NorOperator}
Evalutes a boolean and returns the opposite boolean value.
Parameters:
Name
Type
Description
expression
Expression
Any valid expression.
See:
View Source
index.ts , line 2287
Example
$nor('$a', '$b');
// returns
{ $nor: ['$a', '$b'] }
#
$not(expression) → {NotOperator}
Evalutes a boolean and returns the opposite boolean value.
Parameters:
Name
Type
Description
expression
Expression
Any valid expression.
See:
View Source
index.ts , line 2301
Example
$not('$myVar');
// returns
{ $not: '$myVar' }
#
$objectToArray(object) → {ObjectToArrayOperator}
Converts a document to an array.
Parameters:
Name
Type
Description
object
ObjectExpression
Any valid expression that evaluates to an
expression.
See:
View Source
index.ts , line 2312
Returns:
Type:
ObjectToArrayOperator
#
$out(collection, dbopt ) → {OutExpression}
Parameters:
Name
Type
Attributes
Description
collection
MixedCollectionName
The collection name or Collection object
to output to.
db
string
<optional>
The output database name.
See:
View Source
index.ts , line 619
Returns:
An $out expression accoring to argument input.
Type:
OutExpression
Examples
Basic
$out('myCollection');
// returns
{ $out: 'myCollection' }
With db
$out('myCollection', 'myDb');
// returns
{ $out: { coll: 'myCollection', db: 'myDb' } }
#
$pow(expression1, expression2) → {PowOperator}
Raises a number to the specified exponent and retuns the result.
Parameters:
Name
Type
Description
expression1
NumberExpression
A number of any valid expression that
resolves to a number.
expression2
NumberExpression
A number of any valid expression that
resolves to a number.
See:
View Source
index.ts , line 2327
#
$project(expression) → {ProjectStage}
Passes along the documents with the specified fields to the next stage in
the pipeline.
Parameters:
Name
Type
Description
expression
ObjectExpression
Refer to documentation.
See:
View Source
index.ts , line 638
Example
$project({ x: '$y' });
// returns
{ $project: { x: '$y' } }
#
$push(expression, expression) → {PushOperator}
Returns an array of all values that result from applying an expression to
documents.
Parameters:
Name
Type
Description
expression
Expression
expression
Expression
A valid expression.
See:
View Source
index.ts , line 2339
#
$radiansToDegrees(numberOrExpression) → {RadiansToDegreesOperator}
Converts an input value measured in radians to degrees.
Parameters:
Name
Type
Description
numberOrExpression
NumberExpression
A number or an expresison that
resolves to a number.
See:
View Source
index.ts , line 2350
Returns:
Type:
RadiansToDegreesOperator
#
$redact(ifExpr, thenExpr, elseExpr) → {Redaction}
Restricts entire documents or content within documents from being outputted
based on information stored in the documents themselves.
Parameters:
Name
Type
Description
ifExpr
Expression
Any valid expression as long as it resolves to
a boolean.
thenExpr
Expression
Any valid expression as long as it resolves to
the $$DESCEND, $$PRUNE, or $$KEEP system variables.
elseExpr
Expression
Any valid expression as long as it resolves to
the $$DESCEND, $$PRUNE, or $$KEEP system variables.
See:
To Do:
Expand for supporting sub-syntax like: `$redact().cond(...`
Support non-$cond expression
View Source
index.ts , line 675
Returns:
Returns a Redaction object that resembles the $redact
stage whose usage varies based on optional argument input.
Type:
Redaction
Examples
Static Notation
$redact('$isAdmin', '$$KEEP', '$$PRUNE');
Object Notation
$redact('$isAdmin').then('$$KEEP').else('$$PRUNE');
#
$replaceRoot(newRoot) → {ReplaceRootStage}
Replaces the input document with the specified document.
Parameters:
Name
Type
Description
newRoot
string
|
ObjectExpression
The replacement document can be any valid express
See:
View Source
index.ts , line 689
Returns:
Returns a $replaceRoot operator stage.
Type:
ReplaceRootStage
Example
$replaceRoot('$subpath');
// returns
{ $replaceRoot: { newRoot: '$subpath' } }
#
$replaceWith(replacementDocument) → {ReplaceWithStage}
Replaces the input document with the specified document.
Parameters:
Name
Type
Description
replacementDocument
string
|
ObjectExpression
The replacement
document can be any valid express
See:
View Source
index.ts , line 704
Returns:
Returns a $replaceWith operator stage.
Type:
ReplaceWithStage
Example
$replaceWith('$subpath');
// returns
{ $replaceWith: '$subpath' }
#
$round(value, placesopt ) → {RoundOperator}
Rounds a number to a whole integer or to a specified decimal place.
Parameters:
Name
Type
Attributes
Default
Description
value
NumberExpression
A number of any valid expression that
resolves to a number.
places
NumberExpression
<optional>
0
A number of any valid expression that
resolves to an integer between -20 and 100. Defaults to 0 if unspecified.
See:
View Source
index.ts , line 2376
Returns:
A $round operator populated with argument input.
Type:
RoundOperator
Example
$round(10.5) // 10
$round(11.5) // 12
$round(12.5) // 12
$round(13.5) // 14
#
$roundStandard(value, placesopt ) → {LetVarsIn}
Rounds a number to a specified decimal place.
Parameters:
Name
Type
Attributes
Default
Description
value
NumberExpression
A number of any valid expression that
resolves to a number.
places
NumberExpression
<optional>
0
A number of any valid expression that
resolves to an integer between -20 and 100. Defaults to 0 if unspecified.
See:
View Source
index.ts , line 2420
Returns:
Returns an expression that rounds the value accordingly.
Type:
LetVarsIn
Examples
Zero decimal places
$roundStandard('$myVal');
// returns
{ $let: {
input: '$myVal',
in: { $let: {
vars: {
val: { $add: [
'$$input',
{ $cond: { if: { $gte: ['$$input', 0] }, then: 0.5, else: -0.5 } },
] },
},
in: { $subtact: ['$$val', { $mod: ['$$val', 1] }] },
} },
} }
With decimal places
$roundStandard('$myVal', 2);
// returns
{ $let: {
input: '$myVal',
in: { $let: {
vars: {
val: { $add: [
{ $multiply: ['$$input', 2] },
{ $cond: { if: { $gte: ['$$input', 0] }, then: 0.5, else: -0.5 } },
] },
},
in: { $divide: [{ $subtract: ['$$val', { $mod: ['$$val', 1] }] }, 2] },
} },
} },
#
$sampleRate(value) → {SampleRateOperator}
Matches a random selection of input documents.
Parameters:
Name
Type
Description
value
number
A floating point number between 0 and 1.
See:
View Source
index.ts , line 2441
#
$set(expression) → {SetStage}
Adds new fields to documents. (alias of $addFields)
Parameters:
Name
Type
Description
expression
ObjectExpression
Specify the name of each field to add
and set its value to an aggregation expression or an empty object.
See:
View Source
index.ts , line 718
Example
$set({ fullName: $.concat('$firstName', ' ', '$lastName') });
// returns { $set: { fullName: { $concat: ['$firstName', ' ', '$lastName'] } } }
#
$setDifference(expression1, expression2) → {SetDifferenceOperator}
Takes two sets and returns an array containing the elements that only exist
in the first set.
Parameters:
Name
Type
Description
expression1
ArrayExpression
An array or a valid expression that
resolves to an array.
expression2
ArrayExpression
An array or a valid expression that
resolves to an array.
See:
View Source
index.ts , line 2455
Returns:
Type:
SetDifferenceOperator
#
$setIsSubset(expression1, expression2) → {SetIsSubsetOperator}
Takes two arrays and returns true when the first array is a subset of the
second, including when the first array equals the second array, and false
otherwise.
Parameters:
Name
Type
Description
expression1
ArrayExpression
An array or a valid expression that
resolves to an array.
expression2
ArrayExpression
An array or a valid expression that
resolves to an array.
See:
View Source
index.ts , line 2478
Returns:
Type:
SetIsSubsetOperator
#
$sin(numberOrExpression) → {SinOperator}
Returns the sine of a value that is measured in radians.
Parameters:
Name
Type
Description
numberOrExpression
NumberExpression
A number or an expresison that
resolves to a number.
See:
View Source
index.ts , line 2491
#
$sinh(numberOrExpression) → {SinhOperator}
Returns the hyperbolic sine of a value that is measured in radians.
Parameters:
Name
Type
Description
numberOrExpression
NumberExpression
A number or an expresison that
resolves to a number.
See:
View Source
index.ts , line 2502
#
$size(arrayExpression) → {SizeOperator}
Counts and returns the total number of items in an array.
Parameters:
Name
Type
Description
arrayExpression
ArrayExpression
An array or a valid expression that
resolves to an array.
See:
View Source
index.ts , line 2517
Example
$size('$myArray');
// returns
{ $size: '$myArray' }
#
$skip(value) → {SkipStage}
Skips over the specified number of documents that pass into the stage and
passes the remaining documents to the next stage in the pipeline.
Parameters:
Name
Type
Description
value
number
The number of documents to skip.
See:
View Source
index.ts , line 733
Example
$skip(10);
// returns
{ $skip: 10 }
#
$sort(expression) → {SortStage}
Sorts all input documents and returns them to the pipeline in sorted order.
Parameters:
Name
Type
Description
expression
Expression
Refer to documentation.
See:
View Source
index.ts , line 747
Example
$sort({ x: 1 });
// returns
{ $sort: { x: 1 } }
#
$sortByCount(expression) → {SortByCountStage}
Groups incoming documents based on the value of a specified expression, then
computes the count of documents in each distinct group.
Parameters:
Name
Type
Description
expression
Expression
Refer to documentation.
See:
View Source
index.ts , line 762
Example
$sortByCount('$employee');
// returns
{ $sortByCount: '$employee' }
#
$split(value, delimeter) → {SplitOperator}
Divides a string into an array of substrings based on a delimeter.
Parameters:
See:
View Source
index.ts , line 2533
Example
$split('June-15-2013', '-');
// returns
{ $split: ['June-15-2013', '-'] }
#
$sqrt(numberOrExpression) → {SortStage}
Calculates the square root of a positive number and returns the result as a
double.
Parameters:
Name
Type
Description
numberOrExpression
NumberExpression
A number or an expresison that
resolves to a number.
See:
View Source
index.ts , line 2545
#
$strcasecmp(exression1, exression2) → {StrcasecmpOperator}
Performs case-insensitive comparison of two strings.
Parameters:
Name
Type
Description
exression1
StringExpression
A string or any valid expression that
resolves to a string.
exression2
StringExpression
A string or any valid expression that
resolves to a string.
See:
View Source
index.ts , line 2562
Example
$strcasecmp('$quarter', '13q4');
// returns
{ $strcasecmp: ['$quarter', '13q4'] }
#
$strLenBytes(expression) → {StrLenBytesOperator}
Returns the number of UTF-9 encoded bytes in the specified string.
Parameters:
Name
Type
Description
expression
StringExpression
A string or a valid expression that
resolves to a string.
See:
View Source
index.ts , line 2577
Returns:
Type:
StrLenBytesOperator
Example
$strLenBytes('cafeteria');
// returns
{ $strLenBytes: 'cafeteria' }
#
$strLenCP(expression) → {StrLenCpOperator}
Returns the number of UTF-8 code pints in the specified string.
Parameters:
Name
Type
Description
expression
StringExpression
A string or a valid expression that
resolves to a string.
See:
View Source
index.ts , line 2592
Example
$strLenCP('cafeteria');
// returns
{ $strLenCP: 'cafeteria' }
#
$subtract(minuend, subtrahend) → {SubtractOperator}
Subtracts two numbers to return the difference, or two dates to return the
difference in milliseconds, or a date and a number in milliseconds to return
the resulting date.
Parameters:
Name
Type
Description
minuend
NumberExpression
A number of any valid expression that
resolves to a number.
subtrahend
NumberExpression
number of any valid expression that
resolves to a number.
See:
View Source
index.ts , line 2611
Example
$subtract('$price', '$discount');
// returns
{ $subtract: ['$price', '$discount'] }
#
$subtractSafe(minuend, subtrahend) → {SubtractOperator|number}
Safely subtract two numbers returning the difference.
Parameters:
Name
Type
Description
minuend
NumberExpression
|
null
|
undefined
|
boolean
A number of any valid expression that
resolves to a number.
subtrahend
NumberExpression
|
null
|
undefined
|
boolean
number of any valid expression that
resolves to a number.
See:
View Source
index.ts , line 2637
Returns:
Type:
SubtractOperator
|
number
Examples
$subtractSafe('$a', '$b')
// returns
{ $subtract: [{ $ifNull: ['$a', 0] }, { $ifNull: ['$b', 0] }] }
Literal input
$subtractSafe('$a', 1); // returns { $subtract: [{ $ifNull: ['$a', 0] }, 1] }
$subtractSafe(3, '$b'); // returns { $subtract: [3, { $ifNull: ['$b', 0] }] }
$subtractSafe(3, 1); // returns { $subtract: [3, 1] }
$subtractSafe(true, 1); // returns { $subtract: [1, 1]
$subtractSafe(3, false); // returns { $subtract: [3, 0] }
$subtractSafe(3, undefined); // returns { $subtract: [3, 0] }
$subtractSafe(3, null); // returns { $subtract: [3, 0] }
$subtractSafe(undefined, 1); // returns { $subtract: [0, 1] }
$subtractSafe(null, 1); // returns { $subtract: [0, 1] }
#
$sum(expression) → {SumOperator}
Calculates and returns the collective sum of numeric values. Non-numeric
values are ignored.
Parameters:
Name
Type
Description
expression
Expression
Refer to documentation.
See:
To Do:
View Source
index.ts , line 2656
Example
Single operand
$sum('$value');
// returns
{ $sum: '$value' }
#
$switch(arg1opt , arg2opt ) → {Switch}
Evaluates a series of case expressions. When it finds an expression which
evaluates to true, $switch executes a specified expression and breaks out of
the control flow.
Parameters:
Name
Type
Attributes
Description
arg1
DefaultOrBranches
<optional>
Default path or array of branches.
arg2
DefaultOrBranches
<optional>
Default path or array of branches.
See:
View Source
index.ts , line 2741
Returns:
Returns a Switch object that resembles the $switch operator
whose usage varies based on the optional argument input.
_Optional arguments should be provided through their corresponding methods
to complete the expression._
Type:
Switch
Examples
Static Notation
$switch('$$PRUNE', [
$case('$user.isAdministrator', '$$KEEP'),
$case('$document.hasMore', '$$DESCEND'),
]);
With arguments inverted
$switch([
$case('$user.isAdministrator', '$$KEEP'),
$case('$document.hasMore', '$$DESCEND'),
], '$$PRUNE');
Object notation
$switch()
.case('$user.isAdministor', '$$KEEP')
.case('$document.hasMore', '$$DESCEND')
.default('$$PRUNE');
Hybrid Notation
$switch('$$PRUNE')
.case('$user.isAdministor', '$$KEEP')
.case('$document.hasMore', '$$DESCEND');
Return value of all above examples
{
$switch: {
branches: [
{ cond: '$user.isAdministrator', then: '$$KEEP' },
{ cond: '$document.hasMore', then: '$$DESCEND' },
],
default: '$$PRUNE',
},
}
#
$tan(numberOrExpression) → {TanOperator}
Returns the tangent of a value that is measured in radians.
Parameters:
Name
Type
Description
numberOrExpression
NumberExpression
A number or an expresison that
resolves to a number.
See:
View Source
index.ts , line 2752
#
$tanh(numberOrExpression) → {TanhOperator}
Returns the hyperbolic tangent of a value that is measured in radians.
Parameters:
Name
Type
Description
numberOrExpression
NumberExpression
A number or an expresison that
resolves to a number.
See:
View Source
index.ts , line 2763
#
$toDate(expression) → {ToDateOperator}
Converts a value to a date. Will produce an error if the value cannot be
converted.
Parameters:
Name
Type
Description
expression
Expression
Any valid expression.
See:
View Source
index.ts , line 2784
#
$toDecimal(expression) → {ToDecimalOperator}
Converts a value to a decimal. Throws an error if the value cannot be
converted.
Parameters:
Name
Type
Description
expression
Expression
Any valid expression.
See:
View Source
index.ts , line 2795
#
$toDouble(expression) → {ToDoubleOperator}
Converts a value to a double. Throws an error if the value cannot be
converted.
Parameters:
Name
Type
Description
expression
Expression
Any valid expression.
See:
View Source
index.ts , line 2806
#
$toInt(expression) → {ToIntOperator}
Converts a value to an integer. Throws an error if the value cannot be
converted.
Parameters:
Name
Type
Description
expression
Expression
Any valid expression.
See:
View Source
index.ts , line 2817
#
$toLong(expression) → {ToLongOperator}
Converts a value to a long. Throws an error if the value cannot be converted.
Parameters:
Name
Type
Description
expression
Expression
Any valid expression.
See:
View Source
index.ts , line 2827
#
$toLower(expression) → {ToLowerOperator}
Returns a string converted to lowercase.
Parameters:
Name
Type
Description
expression
StringExpression
A string or a valid expression that
resolves to a string.
See:
View Source
index.ts , line 2871
#
$toObjectId(expression) → {ToObjectIdOperator}
Converts a value to an ObjectId. Throws an error if the value cannot be
converted.
Parameters:
Name
Type
Description
expression
Expression
Any valid expression.
See:
View Source
index.ts , line 2838
#
$toString(expression) → {ToStringOperator}
Converts a value to a string. Throws an error if the value cannot be
converted.
Parameters:
Name
Type
Description
expression
Expression
Any valid expression.
See:
View Source
index.ts , line 2849
#
$toUpper(expression) → {ToUpperOperator}
Returns a string converts to uppercase.
Parameters:
Name
Type
Description
expression
StringExpression
A string or a valid expression that
resolves to a string.
See:
View Source
index.ts , line 2860
#
$trunc(expression1, expression2) → {TruncOperator}
Truncates a number to a whole integer or to a specified decimal place.
Parameters:
Name
Type
Description
expression1
NumberExpression
A number of any valid expression that
resolves to a number.
expression2
NumberExpression
A number of any valid expression that
resolves to an integer between -20 and 100. Defaults to 0 if unspecified.
See:
View Source
index.ts , line 2884
#
$tsIncrement(expression) → {TsIncrementOperator}
Returns the incrementing ordinal from a timestamp as a long.
Parameters:
Name
Type
Description
expression
Expression
Any valid expression that resolves to a
timestamp.
See:
View Source
index.ts , line 2895
Returns:
Type:
TsIncrementOperator
#
$tsSecond(expression) → {TsSecondOperator}
Returns the seconds from a timestamp as a long.
Parameters:
Name
Type
Description
expression
Expression
Any valid expression that resolves to a
timestamp.
See:
View Source
index.ts , line 2906
#
$type(Any) → {TypeOperator}
Returns a string that specifies the BSON type of the argument.
Parameters:
Name
Type
Description
Any
Expression
valid expression.
See:
View Source
index.ts , line 2916
#
$unwind(path, preserveNullAndEmptyArraysopt ) → {Unwind}
Deconstructs an array field from the input documents to output a document
for each element.
Parameters:
Name
Type
Attributes
Description
path
string
Field path to an array field.
preserveNullAndEmptyArrays
boolean
|
undefined
<optional>
Keep or prune documents that
don't have at least one value in the array field.
See:
View Source
index.ts , line 819
Returns:
Returns an Unwind object that resembles the $unwind stage
which can be further manipulated using the relevant methods.
Type:
Unwind
Examples
Static Notation
$unwind('$myArray');
// returns { $unwind: '$myArray' }
Static Notation and preserveNullAndEmptyArrays
$unwind('$myArray', true);
// returns { $unwind: { path: '$myArray', preserverNullAndEmptyArray: true } }
Include Array Index
$unwind('$myArray', true).includeArrayIndex('idxName');
// returns { $unwind: { path: '$myArray', preserverNullAndEmptyArray: true, includeArrayIndex: 'idxName' } }