#1 Data Analytics Program in India
₹2,499₹1,499Enroll Now
5 min read
Question 4 of 27easy

What are MongoDB query operators?

Understanding comparison and logical operators.

What You'll Learn

  • Comparison operators
  • Logical operators
  • Array operators

Comparison Operators

code.jsJavaScript
// $eq - Equal
db.users.find({ age: { $eq: 30 } });

// $ne - Not equal
db.users.find({ status: { $ne: "inactive" } });

// $gt, $gte - Greater than (or equal)
db.users.find({ age: { $gt: 25 } });
db.users.find({ age: { $gte: 25 } });

// $lt, $lte - Less than (or equal)
db.users.find({ age: { $lt: 30 } });

// $in - Match any value in array
db.users.find({ status: { $in: ["active", "pending"] } });

// $nin - Not in array
db.users.find({ role: { $nin: ["admin", "moderator"] } });

Logical Operators

code.jsJavaScript
// $and
db.users.find({
  $and: [{ age: { $gte: 25 } }, { status: "active" }]
});

// $or
db.users.find({
  $or: [{ age: { $lt: 20 } }, { age: { $gt: 60 } }]
});

// $not
db.users.find({ age: { $not: { $gt: 30 } } });

// $nor - Neither condition matches
db.users.find({
  $nor: [{ status: "inactive" }, { role: "banned" }]
});

Array Operators

code.jsJavaScript
// $all - Array contains all elements
db.users.find({ tags: { $all: ["mongodb", "nodejs"] } });

// $elemMatch - Element matches all conditions
db.orders.find({
  items: { $elemMatch: { product: "laptop", qty: { $gt: 1 } } }
});

// $size - Array size
db.users.find({ hobbies: { $size: 3 } });