Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/mongodb/13.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Arrays MongoDB聚合:两个数组的总和_Arrays_Mongodb_Vector_Sum_Aggregation Framework - Fatal编程技术网

Arrays MongoDB聚合:两个数组的总和

Arrays MongoDB聚合:两个数组的总和,arrays,mongodb,vector,sum,aggregation-framework,Arrays,Mongodb,Vector,Sum,Aggregation Framework,我想通过MongoDB中的聚合管道对2个数组进行求和 我的数据: { "_id": "1", "Type": "A", "Data": [ [ 0, 1, 0 ] , [ 0, 1, 0 ], [ 2, 0, 0 ] ] } { "_id": "2", "Type": "A", "Data": [ [ 2, 1, 0 ] , [ 0, 6, 0 ], [ 3, 0, 0 ] ] } { "_id": "3", "Type": "B", "Data": [ [ 0, 1, 0 ] , [ 0,

我想通过MongoDB中的聚合管道对2个数组进行求和

我的数据:

{ "_id": "1", "Type": "A", "Data": [ [ 0, 1, 0 ] , [ 0, 1, 0 ],  [ 2, 0, 0 ] ] }
{ "_id": "2", "Type": "A", "Data": [ [ 2, 1, 0 ] , [ 0, 6, 0 ],  [ 3, 0, 0 ] ] }
{ "_id": "3", "Type": "B", "Data": [ [ 0, 1, 0 ] , [ 0, 2, 0 ],  [ 0, 0, 0 ] ] }
我想在数组的每个元素上建立和

0 1 0   2 1 0   2 2 0
0 1 0 + 0 6 0 = 0 7 0
2 0 0   0 0 0   2 0 0
所以我的结果应该是这样的:

{ "_id": {"Type" : "A"}, "Data": [ [ 2, 2, 0 ] , [ 0, 7, 0 ],  [ 2, 0, 0 ] ] }
{ "_id": {"Type" : "B"}, "Data": [ [ 0, 1, 0 ] , [ 0, 2, 0 ],  [ 0, 0, 0 ] ] }
我从元素分组和构建$sum开始:

[{"$group": 
    { "_id": { "Type" : "$Type" },
      "Data": {"$sum" : "$Data"}
    }
}]

这适用于单值数据,如int,但不适用于数组。那么,我该怎么做呢?(我真的希望有一个没有for循环的解决方案)

您可以展开包含索引的数组,然后对索引求和

我提出了这个解决方案,但如果您有大量文档,我认为性能非常糟糕:

db.test.aggregate([
    {$match: {}},
    {$unwind: {path: '$Data', includeArrayIndex: 'l1'}},
    {$unwind: {path: '$Data', includeArrayIndex: 'l2'}},

    {$group: {_id: {type: '$Type', l1: '$l1', l2: '$l2'}, val: {$sum: '$Data'}}},

    {$sort: {'_id.type': 1, '_id.l1': 1, '_id.l2': 1}},
    {$group: {_id: {type: '$_id.type', l1: '$_id.l1'}, l2: {$push: '$val'}}},

    {$sort: {'_id.type': 1, '_id.l1': 1}},
    {$group: {_id: '$_id.type', final: {$push: '$l2'}}},

    {$sort: {_id: 1}}
])
输出为:

{ "_id" : "A", "Data" : [ [ 2.0, 2.0, 0.0 ], [ 0.0, 7.0, 0.0 ], [ 5.0, 0.0, 0.0 ] ] } 
{ "_id" : "B", "Data" : [ [ 0.0, 1.0, 0.0 ], [ 0.0, 2.0, 0.0 ], [ 0.0, 0.0, 0.0 ] ] }

你的意思是:
[[0,1,0],[0,1,0],[2,0,0]]
?哦,我的错误,我会纠正的。是的,这就是为什么我提到没有for循环。上面的管线实际上查看了每个阵列(我的是多文件层,而不仅仅是2层)。我希望有一个类似于Matlab的函数。我已经测试了一段时间,但我真的不喜欢这个解决方案。在Matlab中,它非常简单,我将继续使用Matlab,因为我无论如何都想使用它。如果有人知道其他解决方案,请随时回答!非常感谢。