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" } )
Unfortunately, the preceding query will return both documents. The reason for this is that both documents have
a track with the title called “Smells Like Teen Spirit” and both have a track number 1. If you want to match an entire
document within the array, you can use $elemMatch , as in this example:
> db.media.find ( { Tracklist: { "$elemMatch" : { Title:
"Smells like teen spirit", Track : "1" } } } )
{ "_id" : ObjectId("4c1a86bb2955000000004076"), "Type" : "CD", "Artist" :
"Nirvana", "Title" : "Nevermind", "Tracklist" : [
 
Search WWH ::




Custom Search