Databases Reference
In-Depth Information
},
{
“rating” : 2,
“count” : 176
}
]
This group by function is quite handy for single MongoDB instances but doesn't work in sharded
deployments. Use MongoDB's MapReduce facility to run grouping functions in a sharded MongoDB
setup. A MapReduce version of the grouping function is included right after the group operation is
explained.
The group operation takes an object as an input. This group operation object includes the following
fi elds:
key — The document fi eld to group by. The preceding example has only one fi eld: rat-
ing . Additional group by fi elds can be included in a comma-separated list and assigned
as the value of the key fi eld. A possible confi guration could be - key: { fieldA: true,
fieldB: true} .
initial — Initial value of the aggregation statistic. In the previous example the initial count
is set to 0 .
cond — The query document to fi lter the collection.
reduce — The aggregation function.
keyf (optional) — An alternative derived key if the desired key is not an existing document fi eld.
fi nalize (optional) — A function that can run on every item that the reduce function iterates
through. This could be used to modify existing items.
Theoretically, the example could easily be morphed into a case where ratings for each movie are
grouped by the rating points by simply using the following group operation:
db.ratings.group(
... { key: { movie_id:true, rating:true },
... initial: { count:0 },
... reduce: function(obj, prev) { prev.count++; }
... }
... );
In real cases, though, this wouldn't work for the ratings collection of 1 million items. You would
be greeted instead with the following error message:
Fri Nov 12 14:27:03 uncaught exception: group command failed: {
“errmsg” : “exception: group() can't handle more than 10000 unique keys”,
“code” : 10043,
“ok” : 0
}
The result is returned as a single BSON object and therefore the collection over which the group
operation is applied should not have more than 10,000 keys. This limitation can also be overcome
with the MapReduce facility.
Search WWH ::




Custom Search