Database Reference
In-Depth Information
Matching an Entire Array
If you want to match an entire array within a document, you can use the $elemMatch
operator. This is particularly useful if you have multiple documents within your
collection, some of which have some of the same information. This can make a default
query incapable of finding the exact document you are looking for. This is because the
standard query syntax doesn't restrict itself to a single document within an array.
Let's look at an example that illustrates this principle. For this to work, we need
to add another document to the collection, one that has an identical item in it, but is
otherwise different. Specifically, we'll add another CD from Nirvana that happens to have
the same track on it as the aforementioned CD (“Smells Like Teen Spirit”). However, on
this version of the CD, the song is track 5, not track 1:
{
"Type" : "CD",
"Artist" : "Nirvana",
"Title" : "Nirvana",
"Tracklist" : [
{
"Track" : "1",
"Title" : "You know you're right",
"Length" : "3:38"
},
{
"Track" : "5",
"Title" : "Smells like teen spirit",
"Length" : "5:02"
}
]
}
> nirvana = ( { "Type" : "CD", "Artist" : "Nirvana", "Title" : "Nirvana",
"Tracklist" : [ { "Track" : "1", "Title" : "You Know You're Right", "Length"
: "3:38"}, {"Track" : "5", "Title" : "Smells Like Teen Spirit", "Length" :
"5:02" } ] } )
> db.media.insert(nirvana)
If you want to search for an album from Nirvana that has the song “Smells Like Teen
Spirit” as Track 1 on the CD, you might think that the following query would do the job:
> db.media.find ( { "Tracklist.Title" : "Smells Like Teen Spirit",
"Tracklist.Track" : "1" } )
 
Search WWH ::




Custom Search