如何在 MongoDB 中使用十进制类型 [英] How to use decimal type in MongoDB

查看:18
本文介绍了如何在 MongoDB 中使用十进制类型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何使用标准 C# 驱动程序在 MongoDB 中存储小数?似乎所有的小数都以字符串的形式存储在数据库中.

How can I store decimals in MongoDB using the standard C# driver? It seems that all decimals are stored inside the database as strings.

推荐答案

MongoDB 直到 MongoDB v3.4 才正确支持小数.在此版本之前,它将小数存储为字符串以避免精度错误.

MongoDB doesn't properly support decimals until MongoDB v3.4. Before this version it stored decimals as strings to avoid precision errors.

v3.4 之前将小数存储为字符串,但这会阻止算术运算.$min$avg、...等运算符将不可用.如果精度不是什么大问题,那么您也许可以切换到 double.

Pre v3.4 Store decimals as strings, but this prevents arithmetic operations. Operators as $min, $avg, ... won't be available. If precision is not a big deal, then you might be able to switch to double.

v3.4+您需要确保以下前提条件成立:

v3.4+ You need to make sure the following preconditions are true:

  • MongoDB 服务器至少应为 v3.4.
  • MongoCSharpDriver 至少应为 v2.4.3.
  • 数据库应将 featureCompatibilityVersion 设置为 '3.4'.如果您的数据库是由较旧的 MongoDB 版本创建的,并且您已将服务器升级到 v3.4,则您的数据库可能仍使用较旧的版本.
  • MongoDB server should be at least v3.4.
  • MongoCSharpDriver should be at least v2.4.3.
  • Database should have featureCompatibilityVersion set to '3.4'. If your database has been created by an older MongoDB version and you have upgraded your server to v3.4 your database might still be on an older version.

如果您设置了所有属性,请注册以下序列化程序以使用 decimal128 类型:

If you have all the properties set, then register the following serializers to use the decimal128 type:

BsonSerializer.RegisterSerializer(typeof(decimal), new DecimalSerializer(BsonType.Decimal128));
BsonSerializer.RegisterSerializer(typeof(decimal?), new NullableSerializer<decimal>(new DecimalSerializer(BsonType.Decimal128)));

这篇关于如何在 MongoDB 中使用十进制类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆