Introduction
Array Query Selectors at a Glance

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.
Exploring `$size`
Better Querying with `$all`
Understanding `$elemMatch`

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:

use comic_book_store_db

db.comic_books.findOne(
    { "characters.name": "Iron Man", "characters.alter_ego": "Bruce Banner"  },
    { title: 1, characters: 1, _id: 0 }
)

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:

use comic_book_store_db

db.comic_books.findOne(
    { characters: { $elemMatch: { name: "Spider-Man", alter_ego: "Peter Parker" } } },
    { title: 1, characters: 1, _id: 0 }
)

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".

Summary
Sign up
Join the 1M+ learners on CodeSignal
Be a part of our community of 1M+ users who develop and demonstrate their skills on CodeSignal