2013-04-16 21 views
12

Próbuję proste zapytanie w Mongo, które w MySQL będzie wyglądać tak.Pole Mongo A większe niż pole B

select * from emails where bounceCount > sentCount; 

Do tej pory mam.

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

Ale ten błąd

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

Jak mogę odwołać się sentCount w tej powłoki?

Odpowiedz

12

db.so.find("this.bounceCount > this.sentCount") jest tym, czego szukasz.

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

Dokumentacja: http://docs.mongodb.org/manual/reference/operator/where/

wyjście Shell:

> 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

każdy zdaje wspomnieć $where nie wiedząc, że jest to:

  • powolny
  • niepewny (evaled)
  • JavaScript, nie MongoDB wewnętrzne
  • I, w wersjach przed 2.4, jeden gwintowany i globalny zablokowana

Inną metodą, która byłaby dużo lepsza dla około 99% przypadków jest użycie struktury agregacji:

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

Nie widzę "niezabezpieczonej" części odpowiedzi, którą dałem. –

+0

@JoeFrambach Parametr '$ where' przyjmuje ciąg znaków, podobnie jak przy pisaniu kodu SQL bez biblioteki ucieczki. – Sammaye

+3

Ale to programista pisze zapytanie. W żadnym momencie dane wprowadzone przez użytkownika nigdy nie zostały ocenione –

Powiązane problemy