Querying Embedded Fields and Arrays

Introduction

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!

Querying Nested Fields

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:

JSON
{
   "title": "The Amazing Spider-Man",
   "issue_number": 1,
   "published_year": 1963,
   "writer": {
      "name": "Stan Lee",
      "nationality": "American"
   }
   // Other fields
}

Let's say we want to find a comic book where the writer's name is "Stan Lee". Here's how you do it:

JavaScript
use comic_book_store_db

db.comic_books.findOne(
  { "writer.name": "Stan Lee" },
  { title: 1, writer: 1, _id: 0 }
)

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.

Querying Arrays

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:

JSON
{
   "title": "The Amazing Spider-Man",
   "issue_number": 1,
   "published_year": 1963,
   "genres": ["Action", "Adventure", "Superhero"]
   "characters": [
      { "name": "Spider-Man", "real_name": "Peter Parker" },
      { "name": "Green Goblin", "real_name": "Norman Osborn" }
   ]
   // Other fields
}

Here are some examples of querying arrays in MongoDB:

JavaScript
use comic_book_store_db

// Locate a comic book where the genre includes "Adventure"
db.comic_books.findOne(
  { genres: "Adventure" }, // Note that we're not using brackets here
  { title: 1, genres: 1, _id: 0 }
)

// Find a comic book which has an exact array of genres, in the specified order
db.comic_books.findOne(
  { genres: ["Action", "Adventure", "Superhero"] }, // Note the brackets!
  { title: 1, genres: 1, _id: 0 }
)

// Find a comic book where a character named "Spider-Man" appears
db.comic_books.findOne(
  { "characters.name": "Spider-Man" },
  { title: 1, "characters.name": 1, _id: 0 }
)

`$in` in Action

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