Is there a way to count the number of unique occurrences of a key using the aggregation framework?

1,307 views
Skip to first unread message

Adam Fields

unread,
Jan 23, 2013, 1:26:29 PM1/23/13
to mongod...@googlegroups.com
If I have a bunch of documents where each document has a category id, I can get the documents per category with:

db.documents.aggregate([{$project:{category_id:1, _id:0}}, {$group:{_id:"$category_id", posts:{ $sum : 1 }}}]);

Is there any way to get the number of unique categories without getting the whole return set and counting the number of documents (and is that even possible with the mongo shell)?

Stephen Lee

unread,
Jan 25, 2013, 3:23:27 PM1/25/13
to mongod...@googlegroups.com
Adam, have you tried using the distinct command, http://docs.mongodb.org/manual/reference/method/db.collection.distinct/#db.collection.distinct?  Something like db.documents.distinct('category_id').toArray().length?

Both your suggestion, using the aggregation framework, and mine require using the full collection, but using the distinct command should be a more direct query.

Adam Fields

unread,
Jan 30, 2013, 11:55:16 PM1/30/13
to mongod...@googlegroups.com

On Jan 25, 2013, at 3:23 PM, Stephen Lee <steph...@10gen.com> wrote:

> Adam, have you tried using the distinct command, http://docs.mongodb.org/manual/reference/method/db.collection.distinct/#db.collection.distinct? Something like db.documents.distinct('category_id').toArray().length?
>
> Both your suggestion, using the aggregation framework, and mine require using the full collection, but using the distinct command should be a more direct query.

That looks like it might do exactly what I need. I'll check it out. Thanks!

Ronald Stalder

unread,
Jan 31, 2013, 6:50:36 AM1/31/13
to mongod...@googlegroups.com
don't use toArray() - just distinct(...).length (distinct returns an array)
Reply all
Reply to author
Forward
0 new messages