翻译或纠错本页面

$trunc (aggregation)

On this page

Definition

$trunc

3.2 新版功能.

Truncates a number to its integer.

$trunc has the following syntax:

{ $trunc: <number> }

The <number> expression can be any valid expression as long as it resolves to a number. For more information on expressions, see Expressions.

Behavior

If the argument resolves to a value of null or refers to a field that is missing, $trunc returns null. If the argument resolves to NaN, $trunc returns NaN.

Example Results
{ $trunc: 0 } 0
{ $trunc: 7.80 } 7
{ $trunc: -2.3 } -2

Example

A collection named samples contains the following documents:

{ _id: 1, value: 9.25 }
{ _id: 2, value: 8.73 }
{ _id: 3, value: 4.32 }
{ _id: 4, value: -5.34 }

The following example returns both the original value and the truncated value:

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

The operation returns the following results:

{ "_id" : 1, "value" : 9.25, "truncatedValue" : 9 }
{ "_id" : 2, "value" : 8.73, "truncatedValue" : 8 }
{ "_id" : 3, "value" : 4.32, "truncatedValue" : 4 }
{ "_id" : 4, "value" : -5.34, "truncatedValue" : -5 }