MongoDB高级查询

时间:2011-03-14 16:54:10

标签: c# mongodb mongodb-.net-driver

假设我有一个包含两个属性的Collection:amount和amountreceived是小数。

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

目前我有一个javascript函数,如下所示:

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

我还有一个看起来像这样的集合集:

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

如果我运行db.MyCollection.find(f),则返回的唯一结果是item1。

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

2 个答案:

答案 0 :(得分:2)

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

你也可以要求C#驱动程序存储.NET十进制值,因为BSON加倍,这会导致一些精度损失并且可能会溢出,但对于查询会很好。

答案 1 :(得分:1)

你确定你正确地这样做了吗?你在下面的例子中有一个反例吗?

这是我的示例测试脚本。 (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 }
相关问题