Database Reference
In-Depth Information
The
distinct()
function also takes nested keys when querying; for instance, this
command will give you a list of unique titles of your CDs:
> db.media.distinct ("Tracklist.Title")
[ "In Bloom", "Smells Like Teen Spirit" ]
Grouping Your Results
Last but not least, you can group your results. MongoDB's
group()
function is similar
to SQL's
GROUP BY
function, although the syntax is a little different. The purpose of the
command is to return an array of grouped items. The
group()
function takes three
parameters:
key
,
initial
, and
reduce
.
The
key
parameter specifies which results you want to group. For example, assume
you want to group results by
Title
. The
initial
parameter lets you provide a base for
each grouped result (that is, the base number of items to start off with). By default, you
want to leave this parameter at zero if you want an exact number returned. The
reduce
parameter groups all similar items together. Reduce takes two arguments: the current
document being iterated over and the aggregation counter object. These arguments are
called
items
and
prev
in the example that follows. Essentially, the
reduce
parameter adds
a
1
to the sum of every item it encounters that matches a title it has already found.
The
group()
function is ideal when you're looking for a
tagcloud
kind of function.
For example, assume you want to obtain a list of all unique titles of
any
type of item in
your collection. Additionally, assume you want to group them together if any doubles are
found, based on the title:
> db.media.group (
{
key: {Title : true},
initial: {Total : 0},
reduce : function (items,prev)
{
prev.Total += 13
}
}
)
[
{
"Title" : "Nevermind",
"Total" : 1
},
{
"Title" : "Definitive Guide to MongoDB, The",
"Total" : 2
}
]