Logical Query Operators

Introduction

Hello there and welcome back! In the previous lessons, you were introduced to MongoDB query operators, which enable you to craft more complex queries. Specifically, you covered comparison operators like $gt, $gte, $eq, and others. In this lesson, we'll focus on logical query operators, which allow you to combine multiple conditions to fine-tune your data retrieval. Let's dive in!

Logical Query Operators

In MongoDB, logical query operators are used to filter data based on expressions that evaluate to true or false:

  • $and: Matches documents where all conditions are true.
  • $or: Matches documents where at least one condition is true.
  • $not: Matches documents where the condition is not true.
  • $nor: Matches documents where none of the conditions are true.

Understanding `$and` Operator

The $and operator combines multiple conditions and only matches documents where all conditions are met. Its syntax requires an array of objects, each representing a condition. Let's run the following command to find the comic books with genres including "Adventure" and featuring Spider-Man as one of the characters:

JavaScript
use comic_book_store_db

db.comic_books.find(
  { $and: [ { genres: "Adventure" }, { "characters.name": "Spider-Man" } ] },
  { title: 1, genres: 1, _id: 0 }
).pretty()

Looks a little bit bulky, right? Actually, the $and operator is the default in a MongoDB filter object, so you can omit it to simplify the expression, like so:

JavaScript
use comic_book_store_db

db.comic_books.find(
  { genres: "Adventure", "characters.name": "Spider-Man" },
  { title: 1, genres: 1, _id: 0 }
).pretty()

So why do we need the $and operator at all? Let's imagine we want to use the same field for querying. For example, suppose we want to find comic books that contain both "Sci-Fi" and "Mystic" genres:

JavaScript
use comic_book_store_db

db.comic_books.find(
  { genres: "Sci-Fi", genres: "Mystic" },
  { title: 1, genres: 1, _id: 0 }
).pretty()

This query will give you the wrong result because JSON objects don't allow duplicate fields; it will simply override the earlier value with the latter value. In this specific example, { genres: "Sci-Fi", genres: "Mystic" } will be equivalent to { genres: "Mystic" }. This is where the $and operator comes to the rescue:

JavaScript
use comic_book_store_db

db.comic_books.find(
  { $and: [ { genres: "Sci-Fi" }, { genres: "Mystic" } ] },
  { title: 1, genres: 1, _id: 0 }
).pretty()

This query will correctly find all comic books that belong to both Sci-Fi and Mystic genres. There are no such comics in our collection, by the way.

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