Elements of an array of sums in Mongodb aggregation

I have the following collection with an array cinside each document

{
  {
    id: 1,
    k: 2.2,
    type: "dog",
    c: [ {parentId:1, p:2.2}, {parentId:1, p:1.4} ]
  },

  {
    id: 2,
    k: 4.3,
    type:"cat",
    c: [ {parentId:2, p:5.2}, {parentId:2, p:4.5} ]
  }
}

parentIdinside each subdocument, cis the identifier of the containing document.

I want to group all the documents using typeand in each group to find out the sum kand the sum of all pin all arrays of the group.

I am currently summarizing kin group mode, but summing pin an array of results in the application. I want to do the summation pin DB!

This is what I am doing now:

db.myCol.aggregate([

{ 
  $group: {
    _id: { type: '$type'},
    k: {$sum: '$k'}, // sum k values, very easy!
    // p: {$sum: '$c.0.p'} <==== Does not work, too
    c: {$addToSet: '$c'} // add to each group all c arrays of group members
  }   
}
], function(err, res) {
   // go over c-arrays and sum p values
   var accP = 0; // accumulator for p values
   for ( var i=0; i<res.length; i++ ) {
     var c = res[i].c;
     for (var j=0;j<c.length; j++) {
       var c2 = c[j];
       for ( var k=0; k<c2.length; k++) { // finally got to objects c array
          accP += c2[k].p;
       }
     }
     res[i].c = accP; // replace array with accumulated p value
   }
});
+1
source share
1 answer

$group , $sum, "k" $push, 2D- "c". $unwind, 2D- c. - $group , " p " " "

db.collection.aggregate([
    { '$group': {
        '_id': '$type', 
        'k': { '$sum': '$k' }, 'c': { '$push': '$c' } 
    } }, 
    { '$unwind': '$c' }, 
    { '$unwind': '$c' },
    { '$group': { 
        '_id': '$_id', 
        'k': { '$first': '$k' }, 
        'c': { '$sum': '$c.p' }
    }}
])

:

{ "_id" : "dog", "k" : 2.2, "c" : 3.6 }
{ "_id" : "cat", "k" : 4.3, "c" : 9.7 }

3.2, , $group, $project .

, $sum $project. , $map "p" .

db.collection.aggregate([
    { '$project': { 
        'type': 1, 
        'k': 1, 
        'c': { 
            '$sum': {
                '$map': { 
                    'input': '$c', 
                    'as': 'subc', 
                    'in': '$$subc.p'
                }
            }
        }
    }}, 
    { '$group': { 
        '_id': '$type', 
        'k': { '$sum': '$k' }, 
        'c': { '$sum': '$c' }
    }}
])

:

{ "_id" : "cat", "k" : 4.3, "c" : 9.7 }
{ "_id" : "dog", "k" : 2.2, "c" : 3.6 }
+3

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


All Articles