Py学习  »  MongoDB

MongoDB C驱动程序中的decimal clr类型和anylte筛选器有问题[重复]

user1873415 • 6 年前 • 1689 次点击  

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

Python社区是高质量的Python/Django开发社区
本文地址:http://www.python88.com/topic/38982
 
1689 次点击  
文章 [ 3 ]  |  最新文章 6 年前
Erik Kinding
Reply   •   1 楼
Erik Kinding    6 年前

我最近遇到了这个问题。我通过简单地注释我的对象来解决它:

[BsonRepresentation(BsonType.Decimal128)]
public decimal Price {get; set;}
Adrian
Reply   •   2 楼
Adrian    7 年前

我在使用 RegisterSerializer 方法,正如它抱怨的那样,它已经注册了一个序列化程序,但另一种方法是编写自己的序列化提供程序并使用它。

提供程序如下:

public class CustomSerializationProvider : IBsonSerializationProvider
{
    private static readonly DecimalSerializer DecimalSerializer = new DecimalSerializer(BsonType.Decimal128);
    private static readonly NullableSerializer<decimal> NullableSerializer = new NullableSerializer<decimal>(new DecimalSerializer(BsonType.Decimal128));

    public IBsonSerializer GetSerializer(Type type)
    {
        if (type == typeof(decimal)) return DecimalSerializer;
        if (type == typeof(decimal?)) return NullableSerializer;

        return null; // falls back to Mongo defaults
    }
}

你需要打电话登记

BsonSerializer.RegisterSerializationProvider(new CustomSerializationProvider());
Ramon de Klein
Reply   •   3 楼
Ramon de Klein    8 年前

MongoDB在3.4版之前不支持小数。在此版本之前,它将小数存储为字符串,以避免精度错误。

3.4版之前 将小数存储为字符串,但这会阻止算术运算。操作员 $min , $avg ,…不可用。如果精度不是什么大问题,那么您可以切换到 double .

V3.4+ 您需要确保以下前提条件是正确的:

  • MongoDB服务器应至少为v3.4。
  • MongoCSharpDriver应至少为2.4.3版。
  • 数据库应该有 featureCompatibilityVersion 设置为 '3.4' . 如果您的数据库是由较旧的MongoDB版本创建的,并且您已将服务器升级到v3.4版,那么您的数据库可能仍在较旧的版本上。

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

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