MongoDB Aggregation: Merge Two Arrays

I have the following type of documents stored in a collection.

{ "_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}, ... ] } 

I want to calculate the aggregated value from the first, second, ..., nth value in the arrays of threads and busy. The order in the array must be preserved. Assuming I want to calculate the amount. The result should look like this:

 { "_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}, ... ] } 

I tried to solve this problem using the aggregation infrastructure, but my current approach does not preserve order and produces a lot of sums.

 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"} } } ]) 

I am not sure that this problem can be solved using the aggregation structure, so a solution using MapReduce will also be fine. How can I get the desired result?

+6
source share
1 answer

An alternative solution without any aggregation structure and 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); }); }); 
0
source

Source: https://habr.com/ru/post/976345/


All Articles