MongoDB: Filtering an Array
Adding to this old post on querying arrays and building on the $ operators lesson from the M102 course on the 10gen website, let's see how to get only the interesting elements of an array.
Let's say we have a coders collection. A generic document looks like this:
{ id: "0001", name: "DeK", gender: "M", country: "Italy", codesIn: "Java" friendWith: [ {name: "Dude", codesIn: "PHP", gender: "M"}, {name: "Dork", codesIn: ["Haskell", "Perl"], gender: "M"}, {name: "Derp", codesIn: "JavaScript"} {name: "Derpina", codesIn: "Perl", gender: "F"} ] }
To match multiple values on multiple elements of an array, the $elemMatch operator is provided:
db.coders.find(friendWith: {$elemMatch: {codesIn: "Perl", gender: "F"}})
will return an array containing only Derpina, that is the element that both codes in Perl and is a female. For an or match, that is to get elements that are either Perl coders or females, standard dot notation will just do:
db.coders.find({friendWith.codesIn: "Perl", friendWith.gender: "F"})
will return an array with Dork and Derpina. Finally, a query on a subdocument:
db.coders.find({friendWith: {codesIn: "Perl", gender: "F"}})
will look for friends with exactly this structure: code in Perl, gender is female and have no name. In our example, DeK has no friends with this features.














