Database Reference
In-Depth Information
Retrieving a Single Document
So far we've only looked at examples that show how to retrieve multiple documents. If you want to receive
only one result, however, querying for all documents—which is what you generally do when executing a
find()
function—would be a waste of CPU time and memory. For this case, you can use the
findOne()
function to retrieve
a single item from your collection. Overall, the result is identical to what occurs when you append the
limit(1)
function, but why make it harder on yourself than you should?
The syntax of the
findOne()
function is identical to the syntax of the
find()
function:
> db.media.findOne()
It's generally advised to use the
findOne()
function if you expect only one result.
Using the Aggregation Commands
MongoDB comes with a nice set of aggregation commands. You might not see their significance at first, but once
you get the hang of them, you will see that the aggregation commands form an extremely powerful set of tools.
For instance, you might use them to get an overview of some basic statistics about your database. In this section,
we will take a closer look at how to use three of the functions from the available aggregate commands:
count
,
distinct
,
and
group
.
In addition to these three basic aggregation commands, MongoDB also includes an aggregation framework.
This powerful feature will allow you to calculate aggregated values without needing to use the—often overly
complex—map/reduce framework. The aggregation framework will be discussed in Chapter 5.
Returning the Number of Documents with count()
The
count()
function returns the number of documents in the specified collection. So far we've added a number of
documents in the
media
collection. The
count()
function can tell you exactly how many:
> db.media.count()
2
You can also perform additional filtering by combining
count()
with conditional operators, as shown here:
> db.media.find( { Publisher : "Apress", Type: "Book" } ).count()
1
This example returns only the number of documents added in the collection that are published by Apress and of
the type Book. Note that the
count()
function ignores a
skip()
or
limit()
parameter by default. To ensure that your
query doesn't skip these parameters and that your count results will match the
limit
and/or
skip
parameters,
use
count(true)
:
> db.media.find( { Publisher: "Apress", Type: "Book" }).skip ( 2 ) .count (true)
0