Welcome! In this lesson, we’ll explore how to query nested fields and arrays in MongoDB. Additionally, we will cover two comparison operators, $in
and $nin
, that were not discussed in the previous lesson. Let's get started!
When documents contain nested fields, like sub-documents, querying can be achieved using dot notation. For example, consider a document in our comic_book_store_db
database:
Let's say we want to find a comic book where the writer's name is "Stan Lee". Here's how you do it:
This query searches within the sub-document writer
for the field name
. Note that writer.name
should be in quotes; otherwise, the .
will cause an error in your query.
Arrays are common in many documents. Our comic_book_store_db
has fields like genres
and characters
, which are arrays. Here's an example of a document containing arrays:
Here are some examples of querying arrays in MongoDB:
The $in
operator is used to match any value within an array of specific values. If we want a comic book that belongs to either 'Action' or 'Adventure' genres:
Conversely, the $nin
operator matches any value that does not exist in the specified array. To find a comic book where the writer's nationality is not "American" or "British":
In this lesson, we've explored querying nested fields and arrays within MongoDB documents. We used dot notation to dig into sub-documents and arrays, and powerful operators like $in
and $nin
to refine our queries. Practice these techniques to enhance your MongoDB querying skills and easily navigate complex document structures. Keep experimenting!
