Introduction
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:

{
   "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:

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:

{
   "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:

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

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:

use comic_book_store_db

db.comic_books.findOne(
  { genres: { $in: ["Action", "Adventure"] } },
  { title: 1, genres: 1, _id: 0 }
)
Using `$nin`

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

use comic_book_store_db

db.comic_books.findOne(
  { "writer.nationality": { $nin: ["American", "British"] } },
  { title: 1, writer: 1, _id: 0 }
)
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