Unknown MongoDB GROUP BY and COUNT keys
I'm trying to GROUP BY and COUNT every key in every Mongo document, but the keys can be different from document to document. I know how to group and count by explicitly naming each key like this:
db.test.aggregate([{"$group" : {_id:"$vcenter", count:{$sum:1}}}])
but how can I iterate over every key of every document without calling the keys. I think the function is mapreduce?
Here is an example document: "key1": "vmx", "key2": "type", "key3": "cpu-idle",
and I'm looking for how many records for such a key: "Key1": 1564 "Key2": 1565 "Key3": 458
+3
source to share
1 answer
Yes, I can only think about mapreduce, since the _id parameter is required in the aggregated $ group . So I will write
map
function map(){for(var prop in this){emit(prop,1)}}
reduce
function reduce(key,values){return values.length;}
execute command
db.inputCollectionName.mapReduce(map,reduce,{out:"outputCollectionName"})
Then you should find in your output collection something like
{ "_id" : "key1", "value" : 1564 }
{ "_id" : "Key2", "value" : 1565 }
{ "_id" : "Key3", "value" : 458 }
Is this good for you?
0
source to share