$trunc

The `$trunc` operator truncates a number to a specified decimal place.

Syntax

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

Parameters

<number>stringrequired

The number to truncate.

<decimal place>stringrequired

The decimal place to truncate the specified number to. A positive value truncates to the right of the decimal point, and a negative value truncates to the left of the decimal point.

Examples

Sample Data

{
  "_id": "0fcc0bf0-ed18-4ab8-b558-9848e18058f4",
  "location": { "lat": -89.2384, "lon": -46.4012 }
}

Fetch truncated location coordinates

Retrieve the truncated coordinates of stores using the $trunc operator.

Query:

db.stores.aggregate([
  {
    $project: {
      truncatedLat: { $trunc: ["$location.lat", 2] }
    }
  }
])

Output:

[
  {
    "_id": "39acb3aa-f350-41cb-9279-9e34c004415a",
    "name": "First Up Consultants | Bed and Bath Pantry",
    "location": { "lat": 87.2239, "lon": -129.0506 },
    "truncatedLatitute": 87,
    "truncatedLongitude": -129
  }
]