0
0
MongoDBquery~5 mins

$or operator behavior in MongoDB

Choose your learning style9 modes available
Introduction

The $or operator helps find documents that match at least one of several conditions. It makes searching flexible by allowing multiple options.

You want to find users who live in either New York or Los Angeles.
You want to get products that are either on sale or have free shipping.
You want to find orders that are either pending or shipped.
You want to search for books written by either Author A or Author B.
You want to filter events happening either today or tomorrow.
Syntax
MongoDB
db.collection.find({ $or: [ { condition1 }, { condition2 }, ... ] })

The $or operator takes an array of conditions inside curly braces.

It returns documents that satisfy at least one of the conditions.

Examples
Find users who live in New York or Los Angeles.
MongoDB
db.users.find({ $or: [ { city: "New York" }, { city: "Los Angeles" } ] })
Find products that cost less than 20 or are on sale.
MongoDB
db.products.find({ $or: [ { price: { $lt: 20 } }, { onSale: true } ] })
Find orders that are either pending or shipped.
MongoDB
db.orders.find({ $or: [ { status: "pending" }, { status: "shipped" } ] })
Sample Program

This example inserts four employees and then finds those who work in HR or live in Chicago.

MongoDB
db.employees.insertMany([
  { name: "Alice", department: "HR", city: "New York" },
  { name: "Bob", department: "IT", city: "Chicago" },
  { name: "Carol", department: "HR", city: "Los Angeles" },
  { name: "Dave", department: "Finance", city: "New York" }
])

db.employees.find({ $or: [ { department: "HR" }, { city: "Chicago" } ] })
OutputSuccess
Important Notes

If no documents match any condition, the result is empty.

Conditions inside $or can be any valid query expressions.

You can combine $or with other operators for complex queries.

Summary

$or finds documents matching at least one condition.

Use it to search with multiple options easily.

It takes an array of conditions and returns matching documents.