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

Mongo Shell中toLocaleString()函数失效及数字格式化替代方案咨询

Why isn't toLocaleString() working in Mongo Shell, and how else can I format numbers with commas?

First off, let's spot the obvious typo in your code—you wrote numer2.toLocaleString() instead of number2.toLocaleString() (missing a 'b' in the variable name!). That's why your function wasn't working: numer2 is undefined, so the code throws a reference error under the hood, and Mongo Shell falls back to returning the original number2 value instead of the formatted string.

Now, let's dig into the toLocaleString() behavior and other solutions:

1. Fix the typo + check your locale configuration

Mongo Shell (built on the SpiderMonkey JS engine) does support toLocaleString(), but it relies on your system's locale settings. If your shell environment doesn't have a locale that uses comma separators for thousands (like en_US.UTF-8), the method will just return the unformatted number string.

Steps to fix:

  • First, correct the variable name in your function:
    db.system.js.save({
      _id:"testValue", 
      value: function(){ 
        var number2 = 1234.56789; 
        const valueFormatted = number2.toLocaleString(); 
        return valueFormatted 
      } 
    })
    
  • If you still don't see commas, start Mongo Shell with a specific locale that supports thousands separators:
    LC_ALL=en_US.UTF-8 mongo
    
  • Now call db.eval("testValue()")—you should get "1,234.56789" as expected.

2. Manual formatting (no locale dependency)

If you want a solution that works regardless of system locale, write a custom function to add commas using regex:

db.system.js.save({
  _id:"formatWithCommas", 
  value: function(num){ 
    if (typeof num !== 'number') return num;
    // Regex adds commas to thousands place
    return num.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ",");
  } 
})

Test it with:

db.eval("formatWithCommas(1234.56789)")

This will reliably return "1,234.56789" without relying on external locale settings.

3. Format during aggregation (for query results)

If you need to format numbers directly in a query instead of a stored function, use MongoDB's aggregation framework (works on MongoDB 4.2+):

db.yourCollection.aggregate([
  {
    $project: {
      formattedNumber: {
        $replaceAll: {
          input: { $toString: "$yourNumberField" },
          find: /(\d)(?=(\d{3})+(?!\d))/g,
          replacement: "$1,"
        }
      }
    }
  }
])

This will add commas to the yourNumberField values in your query results.

内容的提问来源于stack exchange,提问作者Dinil Vamanan

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.26 09:39:09