MongoDB高级查询

问题描述:

比方说,我有一个具有两个属性的集合:金额和金额是小数。MongoDB高级查询

我想编写一个查询,它将返回集合中符合金额大于收到金额标准的项目。

目前,我有一个JavaScript函数,看起来像这样:

f = function() { return this.amount > this.amountreceived;} 

我也有一个收集组,看起来像这样:

item1 : amount = 50, amountreceived = 0; 
item2 : amount = 50, amountreceived = 25; 

如果我跑db.MyCollection.find(f)返回唯一的结果就是物品1 。

关于为什么该查询不会返回这两个结果的任何想法?

+0

有人认为它与驱动程序如何存储小数有关吗? – strickland 2011-03-14 17:08:16

我假设你使用的是C#的驱动程序?由于BSON没有十进制数据类型,因此C#驱动程序必须以某种方式表示.NET十进制值。默认的表示形式是一个字符串,这对于不失去任何精度,但对于查询不利。

您还可以让C#驱动程序将.NET十进制值存储为BSON双精度值,这会导致一些精度损失并可能溢出,但对查询很有用。

+0

感谢您的回应,我只是存储一个布尔值来表示这个逻辑。 – strickland 2011-03-14 17:25:59

您确定您正确地做到了这一点吗?你有下面我的例子的反例吗?

这里是我的示例测试脚本,它的工作原理。 (db.foo为空)

MongoDB shell version: 1.6.5 
connecting to: test 
> db.foo.insert({_id : 1, amount : 50, amtreceived : 100 }) 
> db.foo.insert({_id : 2, amount : 50, amtreceived : 25 }) 
> db.foo.insert({_id : 3, amount : 50, amtreceived : 0 }) 
> db.foo.find() 
{ "_id" : 1, "amount" : 50, "amtreceived" : 100 } 
{ "_id" : 2, "amount" : 50, "amtreceived" : 25 } 
{ "_id" : 3, "amount" : 50, "amtreceived" : 0 } 
> f = function() { return this.amount > this.amtreceived; } 
function() { 
    return this.amount > this.amtreceived; 
} 
> db.foo.find(f) // expect 2 & 3 
{ "_id" : 2, "amount" : 50, "amtreceived" : 25 } 
{ "_id" : 3, "amount" : 50, "amtreceived" : 0 } 
+0

我在发送之前运行了相同的测试,并且工作正常。我现在认为它与驱动程序如何存储小数有关。 – strickland 2011-03-14 17:16:00

+0

我在这里使用驱动程序:https://github.com/mongodb/mongo-csharp-driver – strickland 2011-03-14 17:17:02