Reputation: 321
Here is my collection structure...
{
"_id": ObjectId("5316f53228551c0af600019b"),
"age_range": {
"min": NumberInt(21)
},
"likes": {
"data": {
"0": {
"category": "Tv show",
"name": "Those Who Kill on A&E",
"created_time": "2014-03-03T15:08:02+0000",
"id": "629689387051864"
},
"1": {
"category": "Journalist",
"name": "Robin Roberts",
"created_time": "2014-02-24T18:02:43+0000",
"id": "780950061932847"
}
},
{
"_id": ObjectId("5316f53228551c0af600019b"),
`
I need to fetch total number of users likes for each category. For example
Category Name: Journalist
Total users: 10
Upvotes: 0
Views: 67
Reputation: 1926
try this (collection should be the collection that you have)
var mapFunction = function() {
for (a in this.likes.data){
var name = this.likes.data[a].category;
emit(name, 1);
}
}
var reduceFunction = function(key, val){
return Array.sum(val);
}
db.collection.mapReduce(mapFunction, reduceFunction, {out: "myresult"});
db.myresult.find();
Upvotes: 2