2

I am fairly new to MongoDB and I am playing with the aggregate framework. One of the examples from the documentation shows the following, which returns total number of new user joins per month and lists the month joined:

db.users.aggregate(
  [
    { $project : { month_joined : { $month : "$joined" } } } ,
    { $group : { _id : {month_joined:"$month_joined"} , number : { $sum : 1 } } },
    { $sort : { "_id.month_joined" : 1 } }
  ]
)

The code outputs the following:

{
  "_id" : {
    "month_joined" : 1
  },
  "number" : 3
},
{
  "_id" : {
    "month_joined" : 2
  },
  "number" : 9
},
{
  "_id" : {
    "month_joined" : 3
  },
  "number" : 5
}

Is it possible to also have each object contain the sum of all users that have joined since the start, so I don't have to run over the objects programmatically and calculate it myself?

Example desired output:

{
  "_id" : {
    "month_joined" : 1
  },
  "number" : 3,
  "total": 3
},
{
  "_id" : {
    "month_joined" : 2
  },
  "number" : 9,
  "total": 12
},
{
  "_id" : {
    "month_joined" : 3
  },
  "number" : 5,
  "total": 17
}
Cristian Lupascu
  • 39,078
  • 16
  • 100
  • 137
user602525
  • 3,126
  • 4
  • 25
  • 40
  • 2
    The example would be a loop with only 12 iterations (12 months). :) It's not a natural fit for Aggregation, and I'd suggest you consider implementing it on the client. – WiredPrairie Jul 14 '13 at 16:15
  • 1
    Sure in this problem, it's only 12 iterations. But you can imagine a much larger problem. This is just a sample. – user602525 Jul 14 '13 at 16:24
  • Again, I don't know that there's actually an efficient and practical way to do this with the Aggregation framework. As I said, it would be better to apply the running total on the client. If you're using the AF, it's going to be a limited result set anyway. – WiredPrairie Jul 14 '13 at 18:40
  • I ended up implementing on the client side. Can you explain what you mean by "If you're using the AF, it's going to be a limited result set anyway?" Thanks – user602525 Jul 15 '13 at 16:51
  • The results wouldn't exceed 16MB in the aggregation framework (as that's the limit for the results) – WiredPrairie Jul 15 '13 at 17:36
  • http://stackoverflow.com/questions/19543459/add-the-index-of-each-array-element-to-the-element-itself/19611318#19611318 – Asya Kamsky Oct 26 '13 at 20:11

0 Answers0