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

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:

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:

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:

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.

Understanding `$or` Operator
Understanding `$nor` Operator
Understanding `$not` Operator
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