Database Reference
In-Depth Information
The find() function provides the easiest way to retrieve data from multiple documents within one of your
collections. This function is one that you will be using often.
Let's assume that you have inserted the preceding two examples into a collection called media in the library
database. If you were to use a simple find() function on this collection, you would get all of the documents you've
added so far printed out for you:
> db.media.find()
{ "_id" : "ObjectId("4c1a8a56c603000000007ecb"), "Type" : "Book", "Title" :
"Definitive Guide to MongoDB 2nd ed., The", "ISBN" : "978-1-4302-5821-6", "Publisher" :
"Apress", "Author" : ["Hows, David ", "Plugge, Eelco", "Membrey, Peter", "Hawkins, Tim"]}
{ "_id" : "ObjectId("4c1a86bb2955000000004076"), "Type" : "CD", "Artist" :
"Nirvana", "Title" : "Nevermind", "Tracklist" : [
{
"Track" : "1",
"Title" : "Smells Like Teen Spirit",
"Length" : "5:02"
},
{
"Track" : "2",
"Title" : "In Bloom",
"Length" : "4:15"
}
] }
This is simple stuff, but typically you would not want to retrieve all the information from all the documents in
your collection. Instead, you probably want to retrieve a certain type of document. For example, you might want to
return all the CDs from Nirvana. If so, you can specify that only the desired information is requested and returned:
> db.media.find ( { Artist : "Nirvana" } )
{ "_id" : "ObjectId("4c1a86bb2955000000004076"), "Type" : "CD", "Artist" :
"Nirvana", "Title" : "Nevermind", "Tracklist" : [
{
"Track" : "1",
"Title" : "Smells Like Teen Spirit",
"Length" : "5:02"
},
{
"Track" : "2",
"Title" : "In Bloom",
"Length" : "4:15"
}
] }
Okay, so this looks much better! You don't have to see all the information from all the other items you've added
to your collection, only the information that interests you. However, what if you're still not satisfied with the results
returned? For example, assume you want to get a list back that shows only the titles of the CDs you have by Nirvana,
ignoring any other information, such as track lists. You can do this by inserting an additional parameter into your
query that specifies the name of the key that you want to return, followed by a 1 :
> db.media.find ( {Artist : "Nirvana"}, {Title: 1} )
{ "_id" : ObjectId("4c1a86bb2955000000004076"), "Title" : "Nevermind" }
Search WWH ::




Custom Search