Array Query Selectors in MongoDB comprise a set of operators designed to handle queries specific to array fields. These selectors include:
- $size: Finds documents where an array contains a specified number of elements.
- $all: Finds documents where an array contains all the specified elements.
- $elemMatch: Finds documents containing an array element that matches all specified criteria.
Imagine that you want to find a comic book where one of the characters is named Iron Man with the alter ego Bruce Banner. Given that Iron Man's alter ego is Tony Stark, this search should return no results, right?
Let's execute the query:
Unexpectedly, it returns The Avengers comic book. What's the problem? The problem is that this query finds a comic book where there is a character named Iron Man and there is a character with the alter ego Bruce Banner (not necessarily the same character).
To write the correct query, you can use the $elemMatch operator, which will find a comic book that has a character matching all specified criteria at once:
In this query, we search for a document in the comic_books collection where the characters array contains an object with name set to "Spider-Man" and alter_ego set to "Peter Parker".
