【发布时间】:2017-03-30 20:06:36
【问题描述】:
使用mongodb 3.4.3版,c#驱动(nuget MongoDb.Driver) 2.4.3版
给定一个具有decimal 类型的字段Amount 的类,以及这种类型的mongodb 集合。查询集合中金额大于或小于某个值的条目会给出不正确的结果。将类型更改为“int”时,代码行为正确。在 MongoDb 中使用十进制字段时是否存在一些问题?
下面的示例代码说明了这个问题。
class C
{
public int Id { get; set; }
public string Description { get; set; }
public decimal Amount { get; set; }
}
// assumes a locally installed mongodb
var connectionstring = "mongodb://localhost:27017/test";
var mongo = new MongoClient(connectionstring);
var db = mongo.GetDatabase("test");
db.DropCollection("testcollection");
db.CreateCollection("testcollection");
var collection = db.GetCollection<C>("testcollection");
// populate with 2 instances (amount 1 and amount 10)
collection.InsertMany(new[]
{
new C{Id = 1, Description = "small", Amount = 1},
new C{Id = 2, Description = "large", Amount = 10},
});
// verify that the documents are indeed persisted as expected
var all = collection.AsQueryable().ToList();
Debug.Assert(all.Count == 2);
Debug.Assert(all[1].Amount == 10);
// the assert below inexplicably fails (the query returns no results)
var largerThan5 = collection.AsQueryable().Where(c => c.Amount > 5).ToList();
Debug.Assert(largerThan5.Count == 1);
【问题讨论】:
-
您是否尝试将
[BsonRepresentation(BsonType.Decimal128)]添加到Amount字段? -
@Veeram 我试过了,尝试插入时失败了。
-
@Evk 我无法针对 3.4 服务器对其进行测试。我知道它会因您在 3.2 中的帖子中提到的错误而失败,这是预期的。我期待它可以在 3.4 上运行。
-
@Veeram,你是对的。我确实针对 3.4 进行了测试,但我错过的是 BSON 十进制需要设置
setFeatureCompatibilityVersion,如果没有它,它仍然会失败,并出现与 3.2 中相同的错误。但是使用该设置它可以按预期工作,所以我更新了我的答案。