2013-04-16 14 views
12

Mongoで簡単なクエリを試していますが、これはMySQLのようになります。MongoフィールドAがフィールドBより大きい

select * from emails where bounceCount > sentCount; 

これまでのところ私は持っています。

db.email.find({ bounceCount : { $gt : sentCount } }); 

しかし、私はそのシェルでsentCountを参照するにはどうすればよい

JS Error: ReferenceError: sentCount is not defined (shell):0 

このエラーが出ますか?

答えて

12

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 } 
16

誰もが本当にいることを知らずに$whereを言及するようだ:

db.email.find({ $where: "this.bounceCount > this.sentCount" }); 

オペレータが$の詳細については、MongoDBのドキュメントのページを参照してください。それは:

  • slow
  • JavaScriptの
  • (evaled)安全でない、MongoDBは
  • を内部そして、症例の約99%のために多くの方が良いだろう2.4以前のバージョンでは、シングルスレッドとグローバルロック

上の別の方法ではありません

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

私が与えた答えの「安全でない」部分は表示されません。 –

+0

@JoeFrambach '$ where' paramは、エスケープライブラリを持たずにSQLを書くのと同じように文字列を取ります。 – Sammaye

+3

しかし、それは質問を書く開発者です。ユーザーの入力はいつも評価されていません –

関連する問題