数组中对象的MongoDB聚合总和

时间:2016-09-13 03:02:09

标签: mongodb aggregation-framework

我已经看到了很多关于如何对数组中数组中对象的属性求和的答案,但我试图在文档中对数组中对象的各个属性求和。例如,给定此文档结构:

{
   "id": 1,
   "stats": [
     {
       "number": 100,
       "year": 2014
     },
     {
       "number": 200,
       "year": 2015
     }
]
},


{
   "id": 2,
   "stats": [
     {
       "number": 50,
       "year": 2014
     },
     {
       "number": 75,
       "year": 2015
     }
]
}

所需的输出是:

{
   "stats": [
     {
       "number": 150,
       "year": 2014
     },
     {
       "number": 275,
       "year": 2015
     }
}

我不想总结2014年和2015年的number财产,我想在2014年两个文件中加以总结。

2 个答案:

答案 0 :(得分:1)

db.test.aggregate([
   {  $unwind: "$stats" },
   {
        $group: {
            _id:"$stats.year",
            number:{$sum:"$stats.number"}
        }
    },
    { 
        $group: {
          _id: 0,  
          stats:{ $push:  {year:"$_id",number:"$number"}}
        }
    },
    {  
        $project:{stats:1,_id:0}
    } ])

答案 1 :(得分:0)

这将为您提供所需的输出

class App1 {

private:
    int end = 3;    // this hsould either be declared in the explicit public section you made, or an explicit private section.

public: // do you even indent bro

    /* You can't declare an array like this in a class because
         * the size end is not known at compile time and the compiler
         * needs to know how many bytes to allocate for it. If this
         * was a constant number, you could do it.
         */
    // int list[3];      // this is fine
    int* list_ptr = new int[end];     // this is better; it uses the heap so the compiler is ok not knowing the value of end at compile time. However, you have to remember to free it when you're done.


    void AddInput(){      // You had App1:AddInput here. The namespace declaration is only needed if you are implementing this method outside the enclosing {} braces of the class definition. In this case, because you are implementing it within `class App1{ implementation }`, you are not to add the namespace before the function
        for(int i=0; i<end; i++){
            cout << endl << "Enter elements in array: " << endl;
            int n;      // need to declare n before you can read into it.
            cin >> n;
            list_ptr[i] = n;
        }
    }

    void display(){
        cout << endl << "Display elements: " <<endl;
        for(int i=0; i< end; i++){    // this won't work the way you want; use the variable end
            cout << "Elem " << i << " is: " << list_ptr[i] << endl;       // youa accidentally wrote << end instead of << endl;
        }
        cout << endl;
    }
};  // need to end class declaration with a semicolon