我有以下文档结构
{
"app_id": "DHJFK67JDSJjdasj909",
"date": ISODate("2014-08-07T00:00:00.000Z"),
"event_count": 100,
"events": [
{ "type": 0, "value": 12 },
{ "type": 10, "value": 24 },
{ "type": 20, "value": 36 },
{ "type": 30, "value": 43 }
],
"unique_events": [
{ "type": 0, "value": 5 },
{ "type": 10, "value": 8 },
{ "type": 20, "value": 12 },
{ "type": 30, "value": 56 }
]
}
Run Code Online (Sandbox Code Playgroud)
我试图得到一个event_counts的总和,以及每种类型的unique_events和事件的值.这是我期望的输出类型,其中event_count以及每个事件和unique_events值已按类型求和.
{
"app_id": "DHJFK67JDSJjdasj909",
"date": ISODate("2014-08-07T00:00:00.000Z"),
"event_count": 4345,
"events": [
{ "type": 0, "value": 624 },
{ …Run Code Online (Sandbox Code Playgroud) 我有以下文档结构(本例简化)
{
_id : ObjectId("sdfsdf"),
result : [1, 3, 5, 7, 9]
},
{
_id : ObjectId("asdref"),
result : [2, 4, 6, 8, 10]
}
Run Code Online (Sandbox Code Playgroud)
我想获得这些result数组的总和,但不是总和,而是一个新的数组,对应于元素基础上的原始数组的总和,即
result : [3, 7, 11, 15, 19]
Run Code Online (Sandbox Code Playgroud)
我在这里搜索了无数的问题,有些问题已经接近了(例如这一个,这个,这一个),但我无法完全实现.
我可以得到每个阵列的总和
aggregate(
[
{
"$unwind" : "$result"
},
{
"$group": {
"_id": "$_id",
"results" : { "$sum" : "$result"}
}
}
]
)
Run Code Online (Sandbox Code Playgroud)
这给了我
[ { _id: sdfsdf, results: 25 },
{ _id: asdref, results: 30 } ] …Run Code Online (Sandbox Code Playgroud)