You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

MongoDB聚合操作中如何将浮点数截断为1或2位小数?

How to Truncate the average Field to 1 or 2 Decimal Places in MongoDB Aggregation

Hey there! Looking at your existing aggregation query, you're already doing a solid job calculating the average IMDB rating for each cast member. To truncate that average value to 1 or 2 decimal places, you can use MongoDB's $trunc aggregation operator (which cuts off extra decimals without rounding). If you prefer rounding instead of strict truncation, swap it out for $round—let's break down both options.

Truncate to 1 Decimal Place

Modify the $group stage of your query to wrap the $avg calculation with $trunc, specifying 1 as the number of decimal places to keep:

db.movies.aggregate([
  { $match: { languages: "English", cast: { $exists: true } } },
  { $unwind: "$cast" },
  {
    $group: {
      _id: "$cast",
      numFilms: { $sum: 1 },
      average: { $trunc: [ { $avg: "$imdb.rating" }, 1 ] }
    }
  },
  { $sort: { numFilms: -1 } },
  { $limit: 1 }
])

With this adjustment, your output will be:

{ "_id" : "John Wayne", "numFilms" : 107, "average" : 6.4 }

Truncate to 2 Decimal Places

Just tweak the second parameter in $trunc to 2 to retain two decimal places:

db.movies.aggregate([
  { $match: { languages: "English", cast: { $exists: true } } },
  { $unwind: "$cast" },
  {
    $group: {
      _id: "$cast",
      numFilms: { $sum: 1 },
      average: { $trunc: [ { $avg: "$imdb.rating" }, 2 ] }
    }
  },
  { $sort: { numFilms: -1 } },
  { $limit: 1 }
])

This will return:

{ "_id" : "John Wayne", "numFilms" : 107, "average" : 6.42 }

Rounding Instead of Truncation

If you want to round the value (rather than just cutting off decimals), replace $trunc with $round using the same syntax. For your current average value of 6.424..., rounding to 2 decimals would still give 6.42, but if the average was 6.426, it would round up to 6.43.

Quick Syntax Notes

  • Both $trunc and $round take two arguments: the numeric value to process, and the number of decimal places to retain.
  • $trunc strictly removes extra decimals without adjusting the remaining digits, while $round adjusts based on standard rounding rules.

内容的提问来源于stack exchange,提问作者Rahul Raj

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.20 11:37:31