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

查看:88
本文介绍了如何在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 v3.4,MongoDB才正确支持小数.在此版本之前,它将小数存储为字符串,以避免精度错误.

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天全站免登陆