2015-04-25 36 views
1

使用MongoDB,我該如何編寫此常規SQL語句?如何選擇字段總和大於MongoDB中值的位置

SELECT * FROM table WHERE (field1+field2+field3) > 1 

我已經搞亂$組,$項目,$添加,等等。我覺得我跳舞周圍所有的解決方案,但不能弄明白。

+0

你需要經常執行這個查詢還是這一次拍攝? –

+0

假設它是一次性鏡頭,但是我有興趣看到任一解決方案 – kscott

回答

3

要做到這一點,最簡單的方法是使用$where(說我沒講,這是不可能的聚集做到這一點)

db.table.find({$where: function() { 
    return this.field1 + this.field2 + this.field3 > 1 
    // most probably you have to handle additional cases if some of the fields do not exist. 
}} 

它的優點是,它很容易和直觀,而缺點:

要求數據庫處理集合中每個文檔的JavaScript表達式或 函數。

如果您需要經常進行這種搜索,我會繼續創建一個新字段,其中將存儲3個字段的總和並在其上放置索引。缺點是你必須增加你的應用邏輯。

+0

是的,我一直忘記我可以把JavaScript放在那裏 – kscott

1
> db.test.drop() 
> db.test.insert({ "_id" : 0, "a" : 1, "b" : 1, "c" : 1 }) 
> db.test.insert({ "_id" : 1, "a" : 1, "b" : 1, "c" : 2 }) 
> db.test.aggregate([ 
    { "$project" : { 
     "sum" : { "$add" : ["$a", "$b", "$c" ] } 
    } }, 
    { "$match" : { 
     "sum" : { "$gte" : 4 } 
    } } 
]) 
{ "_id" : 1, "sum" : 4 } 
相關問題