2017-04-09 22 views
1

我在MongoDB中下面集合,讓我們把它稱爲「產品」:MongoDB中尋找到較場另一場加上參數值時

[ 
    { 
    "name"   : "Product X", 
    "warehouseStock" : 50, 
    "reservedStock" : 41 
    }, 
    { 
    "name"   : "Product Y", 
    "warehouseStock" : 50, 
    "reservedStock" : 10 
    } 
] 

我想有一個返回文檔中查找()查詢這個集合的'warehouseStock'小於('reservedStock'+閾值),其中threshold是傳遞給find()查詢的參數。

我嘗試做如下的find()查詢在節點:

var threshold = 10; 
mongo.getDb().collection('products').find({warehouseStock: {$lt:(threshold+'$reservedStock')}}) 

但這似乎並沒有工作。我知道我能做到以下幾點:

mongo.getDb().collection('products').find({warehouseStock: {$lt:threshold}}) 

,但我怎麼可以查詢哪裏

warehouseStock < (reservedStock + threshold) 

所以,如果門檻是= 10,那麼我只會在第一時間拿到這兩個項目的上面的收集示例。

謝謝!

回答

0

您可以使用$where

var threshold = 10; 
mongo.getDb().collection('products').find({ 
    "$where": "this.warehouseStock < (this.reservedStock + " + threshold + ")" 
}).toArray(function(err, items) { 
    console.log(items); 
}); 
+0

太謝謝你了。我也嘗試過$,但我沒有用引號括起來。再次,非常感謝! – Dreamlord