2016-05-31 54 views

回答

2

您可以使用$where操作,您可以在JavaScript表達式傳:

db.getCollection('rss').find({ "$where": "this.duplicates > (this.total_count * 5)" }) 
// sama as db.getCollection('rss').find("this.duplicates > (this.total_count * 5)") 

或使用聚合框架與$cmp運營商這是比以上更有效,因爲使用$where單獨將需要Mongo做收集sca n其中每個文檔都必須從BSON轉換爲JavaScript對象,然後通過表達式運行。索引不能用於滿足表達式,因此性能會大大降低,查詢速度會更慢。


使用$cmp操作會給你更好的性能,因爲它比較兩個值並返回

  • -1,如果第一個值小於第二。
  • 1如果第一個值大於第二個值。
  • 0如果這兩個值相等。

因此,最終的查詢看起來像:

db.getCollection('rss').aggregate([ 
    { 
     "$project": { 
      // Project other fields as required 
      "duplicates": 1, 
      "total_count": 1, 
      "isGreater": { 
       "$cmp": [ 
        "$duplicates", 
        { "$multiply": [ "$total_count", 5 ] } 
       ] 
      } 
     } 
    }, 
    { "$match": { "isGreater": 1 } } 
])