3
votes

I am trying to GROUP BY and COUNT each key in each Mongo document but the keys may differ from document to document. I know how to group and count by explicitly calling each key like this:

db.test.aggregate([{"$group" : {_id:"$vcenter", count:{$sum:1}}}])

but how do I iterate through each key of each document without having to call out keys. I'm thinking a mapreduce function?

Here's a sample document: "key1" : "vmx", "key2" : "type", "key3" : "cpu-idle",

and I'm looking for how many records per key like: "Key1" : 1564 "Key2" : 1565 "Key3" : 458

1
Would be really great if you could show us some sample test documents and the expected output.chridam

1 Answers

0
votes

Yes I can only think at mapreduce, since in the aggregation $group the _id is mandatory. So I'd write

map

function map(){for(var prop in this){emit(prop,1)}}

reduce

function reduce(key,values){return values.length;}

run command

db.inputCollectionName.mapReduce(map,reduce,{out:"outputCollectionName"})

You should then find in your output collection something like

{ "_id" : "key1", "value" : 1564 } 
{ "_id" : "Key2", "value" : 1565 } 
{ "_id" : "Key3", "value" : 458 }

Is that good for you?