0
我需要做一個簡單的蒙戈查詢它類似於這樣的SQL查詢與邏輯表達式比較字段值
Select * from insights where category = 1 and param_count > param_mean + 1
我需要做一個簡單的蒙戈查詢它類似於這樣的SQL查詢與邏輯表達式比較字段值
Select * from insights where category = 1 and param_count > param_mean + 1
理想情況下,你會使用$redact
作爲此聚集的表情,加上初始$match
在至少可能使用索引用於非計算表達式:
db.collection.aggregate([
{ "$match": { "category": 1 } },
{ "$redact": {
"$cond": {
"if": { "$gt": [ "$param_count", { "$add": [ "$param_mean", 1 ] } ] },
"then": "$$KEEP",
"else": "$$PRUNE"
}
}}
])
如果你的MongoDB的「服務器」版本低於2.6沒有$redact
運營商,那麼你可以使用$where
後者評估JA vaScript表達爲布爾值返回結果:
db.collection.find({
"category": 1,
"$where": "this.param_count > this.param_mean + 1"
})
而在語法更短,它需要相當多的處理時間,由於需要評估的JavaScript表達式哪家。
在可能的情況下,您應該使用$redact
,或者完全避免計算,而是將計算的評估值存儲在文檔中。最後的陳述對於「所有」數據庫確實如此。