When performing operations on large data sets, it is often useful to group the results based on the distinct values of one or more fields in a document. You could do this in code after retrieving the documents, but it is much more efficient to have MongoDB do it for you as part of a single request that is already iterating though the documents.
To group the results of a query together, you can use the
group() method on the
Collection object. The
group() request first collects all the documents that match a
query and then adds a
group object to an array, based on distinct values of a set of
keys, performs operations on the
group objects, and returns the array of
group objects. The syntax for the
group() methods is shown below: ...