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
}
6
  • 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. Commented Jul 14, 2013 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. Commented Jul 14, 2013 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. Commented Jul 14, 2013 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 Commented Jul 15, 2013 at 16:51
  • The results wouldn't exceed 16MB in the aggregation framework (as that's the limit for the results) Commented Jul 15, 2013 at 17:36

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.