1

I have following result:

"result" : [ 
    {
        "_id" : "London",
        "count" : 499
    }, 
    {
        "_id" : "Paris",
        "count" : 135
    }, 
    {
        "_id" : "Lviv",
        "count" : 95
    }
]

And here is query:

 {"$group":{
        _id: "$city",
        "count" : {"$sum":1}
    }
 }

So, I want some how to calculate all fields not only grouped. I think it would better to show expected result:

"result" : [ 
    {
        "_id" : "London",
        "count" : 499,
        "total" : 729
    }, 
    {
        "_id" : "Paris",
        "count" : 135,
        "total" : 729
    }, 
    {
        "_id" : "Lviv",
        "count" : 95,
        "total" : 729
    }
]

Expected result has "total" field which calculated as amount of "count" field (499+135+95 = 729). EDITED: I must use only aggregation framework!

Can someone help me with this?

3
  • Why not just add that on the client rather than making the DB do extra work, and send the same data to the client many times? Commented Feb 19, 2014 at 13:10
  • Because client side doesn't have such functionality, I should do this on the server side. Commented Feb 19, 2014 at 15:45
  • What client are you using that can't iterate through the results to produce a total? Commented Feb 19, 2014 at 16:10

2 Answers 2

1

You have to count the total number before:

db.coll.count( ..., function( err, total ) {

and then use that result in your aggregation command:

{
    "$group": {
        _id: "$city",
        count: { "$sum": 1 },
        total: total
}

EDIT:

If you only want to use aggregation framework, try this instead of db.coll.count():

{
    "$group": {
        _id: 1,
        count: { "$sum": 1 }
    }
}
Sign up to request clarification or add additional context in comments.

4 Comments

it doesn't work for me. And probably you made mistake in second group, there is should be "count": {"$first" : "$count"}.
I must correct myself. It is not possible with one call. You need two calls.
it still doesn't work. This one calculate total of all fields: { "$group": { _id: 1, count: { "$sum": 1 } } } But how can I pass "$city" field to the next group operator?
You cannot calculate the total sum of all fields and the sum per city in one (1) call. You have to make two mongo calls.
0

Sounds like db.collection.count() would give you your result actually. This is because you are actually just summing up ALL documents in the collection there.

1 Comment

I need count of grouped fields and total of all fields. Please take a look at my expected result. And one more thing, I should use aggregation framework

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.