MongoDB聚合:组合两个数组

时间:2014-10-07 09:29:39

标签: mongodb mapreduce mongodb-query aggregation-framework

我将以下类型的文档存储在集合中。

{
  "_id" : "318036:2014010100",
  "data": [
    {"flow": [6, 10, 12], "occupancy": [0.0356, 0.06, 0.0856], time: 0},
    {"flow": [2, 1, 4], "occupancy": [0.01, 0.0056, 0.0422], time: 30},
    ...
  ]
}

我想从流和占用数组中的第一个,第二个,......,第n个值计算聚合值。应保留数组中的顺序。假设我想要计算总和。结果应如下所示:

{
  "_id" : "318036:2014010100",
  "data": [
    {"flow": [6, 10, 12], "occupancy": [0.0356, 0.06, 0.0856], sum: [6.0356, 10.006, 12.00856], time: 0},
    {"flow": [2, 1, 4], "occupancy": [0.01, 0.0056, 0.0422], sum: [2.01, 1.0056, 4.0422], time: 30},
    ...
  ]
}

我试图通过使用聚合框架来解决这个问题,但我当前的方法并没有保留排序并产生大量的数据。

db.sens.aggregate([ 
  {$match: {"_id":/^318036:/}}, 
  {$limit: 1}, 
  {$unwind: "$data"}, 
  {$unwind: "$data.flow"}, 
  {$unwind: "$data.occupancy"}, 
  {
    $group: { 
      _id: {id: "$_id", time: "$data.time", o: "$data.occupancy", f: "$data.flow", s: {$add: ["$data.occupancy", "$data.flow"]}}
    }
  }, 
  {
    $group: { 
      _id: {id: "$_id.id", time: "$_id.time"}, occ: { $addToSet: "$_id.o"}, flow: {$addToSet: "$_id.f"}, speed: {$addToSet: "$_id.s"} 
    }
  } 
]) 

我不确定是否可以使用聚合框架解决这个问题,因此使用MapReduce的解决方案也可以。我怎样才能产生预期的结果?

1 个答案:

答案 0 :(得分:0)

既没有聚合框架也没有map / reduce的替代解决方案:

db.sens.find().forEach(function (doc) {
   doc.data.forEach(function(dataElement) {
      var sumArray = [];
      for (var j = 0; j < dataElement.flow.length; j++) {
         sumArray[j] = dataElement.flow[j] + dataElement.occupancy[j];
      }
      dataElement.sum = sumArray;
      collection.save(doc);
   });
});