Database Reference
In-Depth Information
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
Retrieving Unique Values with distinct()
The preceding example shows a great way to retrieve the total number of documents from
a specific publisher. However, this approach is definitely not precise. After all, if you own
more than one book with the same title (for instance, the hardcopy and the e-book), then
you would technically have just one book. This is where distinct() can help you: it will
only return unique values.
For the sake of completeness, you can add an additional item to the collection. This
item carries the same title, but has a different ISBN number:
> document = ( { "Type" : "Book","Title" : "Definitive Guide to MongoDB 2nd
ed., The", ISBN:
"978-1-4302-5821-6", "Publisher" : "Apress", "Author" :
["Hows, David","Membrey, Peter","Plugge, Eelco","Hawkins, Tim"] } )
> db.media.insert (document)
At this point, you should have two topics in the database with identical titles. When
using the distinct() function on the titles in this collection, you will get a total of two
unique items. However, the titles of the two topics are unique, so they will be grouped
into one item. The other result will be the title of the album “Nevermind”:
> db.media.distinct( "Title")
[ "Definitive Guide to MongoDB, The", "Nevermind" ]
Similarly, you will get two results if you query for a list of unique ISBN numbers:
> db.media.distinct ("ISBN")
[ "1-4302-3051-7", "987-4302-3051-9" ]
 
Search WWH ::




Custom Search