- Reference >
- Operators >
- Aggregation Pipeline Operators >
- $isNumber (aggregation)
$isNumber (aggregation)¶
On this page
Definition¶
-
$isNumber
¶ New in version 4.4.
$isNumber
checks if the specified expression resolves to one of the following numeric BSON types:$isNumber
returns:true
if the expression resolves to a number.false
if the expression resolves to any other BSON type,null
, or a missing field.
$isNumber
has the following operator expression syntax:The argument can be any valid expression.
See also
$type (Aggregation)
- returns the BSON type of the argument.$type (Query)
- filters fields based on BSON type.
Example¶
Use $isNumber
to Check If A Field Is Numeric¶
Issue the following operation against the examples.sensors
collection to populate test data:
The following aggregation uses the $addFields
aggregation
stage to add the following fields to each document:
isNumber
- Indicates whether the value ofreading
is an integer, decimal, double, or long.type
- Indicates the BSON type ofreading
.
The aggregation operation returns the following results:
Conditionally Modify Fields using $isNumber
¶
The grades
collection contains data on student grades. The grade
field may either store a string letter grade or a numeric point value.
The following aggregation uses the $addFields
stage to add a
points
field containing the numeric grade value for that course. The
stage uses the $cond
operator to set the value of
points
based on the output of $isNumber
:
- If
true
,grades
already contains the numeric point value. Setpoints
equal togrades
. - If
false
,grades
contains a string letter value. Use$switch
to convert the letter grade to its equivalent point value and assign topoints
.
The aggregation pipeline then uses the $group
stage to
group on the student_id
and calculate the student’s
average
GPA.
The aggregation pipeline outputs one document per unique student_id
with that student’s GPA
grade point average: