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

MongoDB findOne查询后NumberInt类型转为Decimal问题求助

Fixing NumberInt to Decimal Conversion in MongoDB Shell Queries

Got it, let's break down why your order and level fields (stored as NumberInt) are showing up as Decimal after running findOne, and how to fix this.

Why This Happens

MongoDB's shell runs on JavaScript, which only has a single numeric type: 64-bit floating point numbers. When you fetch a document with NumberInt fields, the shell automatically converts those 32-bit integers into JavaScript's Number type. Depending on your shell version or output settings, this conversion might be displayed as a Decimal instead of the original integer format—but rest assured, the underlying value is still an integer (as long as it fits within 32-bit range).

Solutions to Preserve/View Original NumberInt Type

1. View the Document with Canonical BSON Format

To see the exact BSON types (including NumberInt) in your query results, use the tojson function with the canonical: true option. This forces the shell to output the original BSON type notation instead of converting to JavaScript's numeric type:

var obj = db.itemMenu.findOne({"code": "ME0001"});
print(tojson(obj, { canonical: true }));

This will output your document with the original NumberInt values like this:

{ "_id" : ObjectId("599ccef160b543xbf380c99x"), "code" : "ME0001", "description" : "Element 1", "operationCode" : null, "order" : NumberInt(1), "level" : NumberInt(0), "subItems" : [ ] }

2. Manually Convert Back to NumberInt (If Needed)

If you need to work with the NumberInt type in shell scripts or further operations, you can explicitly convert the values back using MongoDB's NumberInt() constructor:

var obj = db.itemMenu.findOne({"code": "ME0001"});
// Convert fields back to NumberInt
obj.order = NumberInt(obj.order);
obj.level = NumberInt(obj.level);

// Verify the type behavior
print("Order value type in shell:", typeof obj.order);
// When saved back to the collection, it will retain the NumberInt type

When you save this modified document back to the collection, MongoDB will preserve the NumberInt type instead of storing it as a floating point or Decimal.

3. Check Client Display Settings (If Using GUI Tools)

If you're using a GUI client like MongoDB Compass instead of the shell, double-check the client's display settings—some tools default to formatting numeric values as Decimals for consistency. Look for options to "show original BSON types" or adjust numeric formatting to display integers correctly.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.25 07:04:15