我的 mongodb 集合中有很多記錄,我需要重新計算一些資訊。
記錄格式:
{
"_id" : someId,
"targetFrom" : ObjectId("603e0355e805140334e79438"),<-- this is ID for search
"targetTo" : null,
"operationPaid" : true,
"type" : "coming", <--- type
"moneyAccount" : someId,
"agent" : null,
"sum" : 5000, <--- sum
}
{
"_id" : someId,
"targetFrom" : null,
"targetTo" : null,
"operationPaid" : true,
"type" : "out", <--- type
"moneyAccount" : someId,
"agent" : ObjectId("603e0355e805140334e79438"),<-- this is ID for search
"sum" : 3000, <--- sum
}
所以,我需要按記錄型別分組并獲取id ObjectId("603e0355e805140334e79438") 的SUM,但搜索的 id 可以是欄位targetFrom或targetTo或代理
對于這個例子,我需要得到結果2000
和5000的到來,并和3000是出來帶
uj5u.com熱心網友回復:
詢問
- 匹配 3 個可能欄位之一中的 ID
- 按 null 分組(所有集合 1 組),如果
type="out"我減去 sum 欄位,否則我添加到 sum 欄位
測驗代碼在這里
aggregate(
[{"$match":
{"$expr":
{"$or":
[{"$eq":["$targetFrom", ObjectId("603e0355e805140334e79438")]},
{"$eq":["$targetTo", ObjectId("603e0355e805140334e79438")]},
{"$eq":["$agent", ObjectId("603e0355e805140334e79438")]}]}}},
{"$group":
{"_id":null,
"sum":
{"$sum":
{"$cond":
[{"$eq":["$type", "out"]}, {"$subtract":[0, "$sum"]}, "$sum"]}}}}])
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/405561.html
標籤:
上一篇:很難索引陣列
