admin管理员组

文章数量:1356948

I'm trying to manage BigInteger on MongoDB. I did a test, but it doesn't seem to work correctly.

It is supposed to have the following poco:

public class Poco
{
   public string MyString { get; set; } = String.Empty;

   [BsonSerializer(typeof(BigIntegerSerializer))]
   public BigInteger MyBigInteger { get; set; } = BigInteger.Zero;
}

And the following serializer:

public class BigIntegerSerializer : SerializerBase<BigInteger>
{
   public override BigInteger Deserialize(
      BsonDeserializationContext context,
      BsonDeserializationArgs args)
   {
      var val = context.Reader.ReadString();
      return BigInteger.Parse(val);
   }

   public override void Serialize(
      BsonSerializationContext context,
      BsonSerializationArgs args,
      BigInteger value)
   {
      context.Writer.WriteString(value.ToString());
   }
}

Now, I use the following code to insert some values:

Poco poco;
for (var counter = 1000; counter < 1100; counter++)
{
   var text = $"name_{counter}";
   poco = new Poco(text, new BigInteger(counter));
   if (!await CheckIfPresent(poco.MyBigInteger))
   {
      await Collection.InsertOneAsync(poco);
   }
}
poco = new Poco($"name_{10940}", 10940);
if (!await CheckIfPresent(poco.MyBigInteger))
{
   await Collection.InsertOneAsync(poco);
}

And I correctly have some rows on database:

[
  {
    "_id": {"$oid": "67e82f61b3297f43eccc469e"},
    "MyBigInteger": "1000",
    "MyString": "name_1000"
  },
  {
    "_id": {"$oid": "67e82f61b3297f43eccc469f"},
    "MyBigInteger": "1001",
    "MyString": "name_1001"
  },
  {
    "_id": {"$oid": "67e82f61b3297f43eccc46a0"},
    "MyBigInteger": "1002",
    "MyString": "name_1002"
  },
  ...
  {
    "_id": {"$oid": "67e82f61b3297f43eccc4702"},
    "MyBigInteger": "10940",
    "MyString": "name_10940"
  }
]

My problem starts when I use the following code to extract/filter data from the database:

var docs = (await
(await Collection
   .FindAsync(x => x.MyBigInteger >= new BigInteger(1095)))
   .ToListAsync())
   .OrderBy(x => x.MyBigInteger);
foreach (var test in docs)
{
   Console.WriteLine($"{test.MyBigInteger} - {test.MyString}");
}


And I receive:

1096 - name_1096
1097 - name_1097
1098 - name_1098
1099 - name_1099

As you can see, it doesn't extract the value "10940." I suppose the database uses a lexicographic string ordering...

I did another test modifying the serialiser to user byte[] instead string (that's because the method new BigInteger(byte[]) is faster than BigInteger.Parse(string)), but the results are even worst...

Any suggestions on how I can solve the problem?

本文标签: How to manage c BigInteger on MongoDBStack Overflow