Mongo字段A大于字段B.

Mit*_*esh 19 mongodb

我正在Mongo中尝试一个简单的查询,在MySQL中看起来像这样.

select * from emails where bounceCount > sentCount;
Run Code Online (Sandbox Code Playgroud)

到目前为止我有.

db.email.find({ bounceCount : { $gt : sentCount } } );
Run Code Online (Sandbox Code Playgroud)

但是我得到了这个错误

JS Error: ReferenceError: sentCount is not defined (shell):0
Run Code Online (Sandbox Code Playgroud)

如何在shell中引用sentCount?

Sam*_*aye 19

每个人似乎都提到它$where而不是真的知道它是:

  • 不安全(被证实)
  • JavaScript,而不是MongoDB内部
  • 而且,在2.4之前的版本中,单线程和全局锁定

对于大约99%的情况,另一种更好的方法是使用聚合框架:

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

  • 但是开发人员正在编写查询.用户输入从未被用过 (5认同)
  • 如果如果如果如果怎么办?这是一个简单的查询.不过,我同意你所有其他方面的意见. (3认同)
  • @JoeFrambach有时候,如果把这些东西放到$ where来自GET或POST或其他什么?我认为我们不能保证这一点,我们不够了解. (2认同)

Fra*_*bot 14

db.so.find("this.bounceCount > this.sentCount") 是你在找什么.

当量: db.so.find({"$where":"this.bounceCount > this.sentCount"})

文档:http://docs.mongodb.org/manual/reference/operator/where/

壳牌产量:

> 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 }
Run Code Online (Sandbox Code Playgroud)


And*_*rik 13

它应该做的伎俩:

db.emails.find({ $expr: { $gt: [ "$bounceCount" , "$sentCount" ] } });
Run Code Online (Sandbox Code Playgroud)

以下是我发现它的参考:https: //docs.mongodb.com/manual/reference/operator/query/expr/#op._S_expr