Getting counts of embedded collections in a MongoDB Document
I am using MongoDB and the 10Gen node.js driver.


I have a collection in MongoDB that has docs similar to this:

    {
     _id: ObjectId( "500310affdc47af710000001" ),
     name:'something',
     tags:['apple','fruit','red'],
     created: Date( 1342378221351 )
    }

What I would like to get is look at all the documents and get a distinct count of all tags across all documents in the collection.  I tried the group function and got this:


    > db.photos.group(
    ... {cond:{}
    ... ,key:{tags:true}
    ... ,initial:{count:0}
    ... ,reduce:function(doc,out){out.count++}
    ... ,finalize:function(out){}});
    [
    	{
    		"tags" : null,
    		"count" : 35
    	},
    	{
    		"tags" : [
    			"#strawberry",
    			"#friutpicture"
    		],
    		"count" : 1
    	}
    ]

Which is not right.  I can get the distinct without the counts like this:

    > db.photos.distinct('tags')
    [
    	"#friutpicture",
    	"#strawberry",
    	"#factory",
    	"#wallpaper",
    	"#bummber",
    	"#test",
    	"#fire",
    	"#watermark"
    ]

but I need the counts.
Getting counts of embedded collections in a MongoDB Document
===

I am using MongoDB and the 10Gen node.js driver.


I have a collection in MongoDB that has docs similar to this:

    {
     _id: ObjectId( "500310affdc47af710000001" ),
     name:'something',
     tags:['apple','fruit','red'],
     created: Date( 1342378221351 )
    }

What I would like to get is look at all the documents and get a distinct count of all tags across all documents in the collection.  I tried the group function and got this:


    > db.photos.group(
    ... {cond:{}
    ... ,key:{tags:true}
    ... ,initial:{count:0}
    ... ,reduce:function(doc,out){out.count++}
    ... ,finalize:function(out){}});
    [
    	{
    		"tags" : null,
    		"count" : 35
    	},
    	{
    		"tags" : [
    			"#strawberry",
    			"#friutpicture"
    		],
    		"count" : 1
    	}
    ]

Which is not right.  I can get the distinct without the counts like this:

    > db.photos.distinct('tags')
    [
    	"#friutpicture",
    	"#strawberry",
    	"#factory",
    	"#wallpaper",
    	"#bummber",
    	"#test",
    	"#fire",
    	"#watermark"
    ]

but I need the counts.