2012-05-05 17 views
0

我測試的MongoDB,這裏是有點例子是讓我驚訝:

> function compare(a,b) { return (a==b); } 

,然後列出我的收藏:

> db.myCol.find() 
{ "_id:" : ObjectId("..."), "name" : "mongo" } 
{ "_id:" : ObjectId("..."), "x" : 3 } 
{ "_id:" : ObjectId("..."), "name" : "mongo", "notName" : "wow" } 

和 - 是完全肯定的:

> compare('mongo','mongo') 
true 

和怪異的一部分:

> db.myCol.find({ $where : "compare(this.name,'mongo')" }) 
{ "_id:" : ObjectId("..."), "x" : 3 } 
> db.myCol.find({ $where : "this.name=='mongo'" }) 
{ "_id:" : ObjectId("..."), "name" : "mongo" } 
{ "_id:" : ObjectId("..."), "name" : "mongo", "notName" : "wow" } 

我希望查詢具有嚴格相反的設置。

回答

2

你得到奇怪結果的原因是你實際上並沒有運行你定義的比較函數。它是在本地定義的,但是您正在mongodb實例上遠程執行命令。什麼是真正發生的是內置的比較正在使用:

> compare 
function (l, r) { 
    return l == r ? 0 : l < r ? -1 : 1; 
} 

> compare('mongo', 'mongo') 
0 

這裏是你如何可以告訴:

> function compare1(a,b) {return a==b} 

> db.myCol.find({ $where : "compare1(this.name,'mongo')" }) 
error: { 
    "$err" : "error on invocation of $where function:\nJS Error: ReferenceError: compare1 is not defined nofile_a:0", 
    "code" : 10071 
} 

有是說明了如何存儲在功能上Server-side Code Execution一個文檔頁面服務器。但是,它也解釋了在可能的情況下不應使用服務器端功能。

+0

好的,有道理。我意識到缺點,但是我沒有注意到,這正是它的工作原理。謝謝 – nimdil

0

簡單忘記服務端代碼執行使用$ where操作符,因爲這很慢,不會使用索引,並會在執行時鎖定服務器進程。