1

After I write a MongoDB aggregate command, I would like to quickly look at the number of results it returned.

Say, my query is something like this: (probably more complex)

db.zipcodes.aggregate( [{ $group :
                            { _id : "$state" } }])

Then, right now I do the following to get a total count:

 db.zipcodes.aggregate( [{ $group :
                            { _id : "$state" }},
                         {'$group': {_id: null, count: {$sum: 1}}}])

Is there another quicker way to get a count of the results of a MongoDB aggregate query?

PS: I've just seen a related question: MongoDB Aggregation: How to get total records count? . Has there been any progress regarding this?

Community
  • 1
  • 1
Phani
  • 3,267
  • 4
  • 25
  • 50
  • Well for MongoDB versions prior to 2.6 the result is always returned as an array, it can optionally be returned as a cursor in recent versions. As such this is all your robomongo interface is doing, by getting the "length" of the array returned. You can do the same thing to. – Neil Lunn Jun 26 '14 at 03:13
  • can you tell me how to get the length of the array when using something like the first query in the question – Phani Jun 28 '14 at 14:02

2 Answers2

1
db.zipcodes.aggregate( [{ $group :
                        { _id : "$state" } },
{
  $count: "total" 
} 
])
Neha Sinha
  • 173
  • 1
  • 6
  • 1
    See "[Explaining entirely code-based answers](https://meta.stackoverflow.com/q/392712/128421)". While this might be technically correct, it doesn't explain why it solves the problem or should be the selected answer. We should educate along with helping solve the problem. – the Tin Man Mar 22 '22 at 04:55
0

One workaround I found so far is to use a MongoDB GUI such as Robomongo. It reports the size of the Result.

enter image description here

Phani
  • 3,267
  • 4
  • 25
  • 50