Mongodb Mongo字段A大于字段B

Mongodb Mongo字段A大于字段B,mongodb,Mongodb,我正在Mongo中尝试一个简单的查询,在MySQL中是这样的 select * from emails where bounceCount > sentCount; 到目前为止我有 db.email.find({ bounceCount : { $gt : sentCount } } ); 但是我得到了这个错误 JS Error: ReferenceError: sentCount is not defined (shell):0 如何引用该shell中的sentCount?db.s

我正在Mongo中尝试一个简单的查询,在MySQL中是这样的

select * from emails where bounceCount > sentCount;
到目前为止我有

db.email.find({ bounceCount : { $gt : sentCount } } );
但是我得到了这个错误

JS Error: ReferenceError: sentCount is not defined (shell):0
如何引用该shell中的sentCount?

db.so.find(“this.bounceCount>this.sentCount”)
是您要查找的

等效:
db.so.find({“$where”:“this.bounceCount>this.sentCount”})

文件:

外壳输出:

> db.so.insert({bounceCount:1, sentCount:2})
> db.so.insert({bounceCount:5, sentCount:3})
> db.so.insert({bounceCount:5, sentCount:4})
> db.so.insert({bounceCount:5, sentCount:7})
> db.so.insert({bounceCount:9, sentCount:7})

> db.so.find()
{ "_id" : ObjectId("516d7f30675a2a8d659d7594"), "bounceCount" : 1, "sentCount" : 2 }
{ "_id" : ObjectId("516d7f37675a2a8d659d7595"), "bounceCount" : 5, "sentCount" : 3 }
{ "_id" : ObjectId("516d7f3b675a2a8d659d7596"), "bounceCount" : 5, "sentCount" : 4 }
{ "_id" : ObjectId("516d7f3d675a2a8d659d7597"), "bounceCount" : 5, "sentCount" : 7 }
{ "_id" : ObjectId("516d7f40675a2a8d659d7598"), "bounceCount" : 9, "sentCount" : 7 }

> db.so.find({"bounceCount":5})
{ "_id" : ObjectId("516d7f37675a2a8d659d7595"), "bounceCount" : 5, "sentCount" : 3 }
{ "_id" : ObjectId("516d7f3b675a2a8d659d7596"), "bounceCount" : 5, "sentCount" : 4 }
{ "_id" : ObjectId("516d7f3d675a2a8d659d7597"), "bounceCount" : 5, "sentCount" : 7 }

> db.so.find("this.bounceCount > this.sentCount")
{ "_id" : ObjectId("516d7f37675a2a8d659d7595"), "bounceCount" : 5, "sentCount" : 3 }
{ "_id" : ObjectId("516d7f3b675a2a8d659d7596"), "bounceCount" : 5, "sentCount" : 4 }
{ "_id" : ObjectId("516d7f40675a2a8d659d7598"), "bounceCount" : 9, "sentCount" : 7 }

您可以使用$where操作符来执行此操作,它允许您在查询中使用Javascript代码

例如,您可以执行以下操作:

db.email.find({ $where: "this.bounceCount > this.sentCount" });
有关$where操作符的更多详细信息,请参见MongoDB文档页面:

每个人似乎都提到了
$where
,但实际上并不知道它是:

  • 不安全(evaled)
  • JavaScript,而不是MongoDB内部
  • 在2.4之前的版本中,单线程和全局锁定
对于大约99%的情况,另一种更好的方法是使用聚合框架:

db.col.aggregate([
    {$project: {ab: {$cmp: ['$bounceCount','$sentCount']}}},
    {$match: {ab:{$gt:0}}}
])

它应该做到这一点:

db.emails.find({ $expr: { $gt: [ "$bounceCount" , "$sentCount" ] } });
以下是我找到它的参考资料:

我没有看到我给出的答案中的“不安全”部分。@JoeFrambach the
$where
param接受字符串,很像编写不带转义库的SQL。但编写查询的是开发人员。用户输入从来都不是evaled@JoeFrambach有时候,如果放入美元的东西来自GET、POST或其他什么东西呢?我不认为我们能保证这一点,我们知道的还不够。如果,如果。这是一个直截了当的问题。不过,我在所有其他方面都同意你的看法。