Q1. What are comparison operators in MongoDB?
Comparison operators include $eq, $ne, $gt, $gte, $lt, $lte, $in, $nin.
Examples:
Examples:
db.users.find({ age: { $gte: 18, $lte: 30 } })
db.users.find({ city: { $in: ["NYC", "LA", "CHI"] } })These operators help filter documents based on field values.Q2. What are logical operators in MongoDB?
Logical operators: $and, $or, $not, $nor. They combine multiple conditions.
Example:
Example:
db.users.find({
$or: [
{ age: { $lt: 20 } },
{ age: { $gt: 50 } }
],
$and: [
{ status: "active" }
]
})Q3. What are element operators?
Element operators like $exists and $type check for the presence or type of a field.
Example:
Example:
db.users.find({ email: { $exists: true } })
db.users.find({ age: { $type: "int" } })Useful for handling missing fields or validating data types.Q4. How do you query arrays in MongoDB?
Array operators include $all, $size, $elemMatch.
Example:
Example:
db.products.find({ tags: "electronics" }) // array contains
db.products.find({ tags: { $all: ["electronics", "sale"] } })
db.products.find({ reviews: { $size: 5 } })Q5. How do you query embedded documents?
Use dot notation:
db.users.find({ "address.city": "New York" })
db.users.find({ "address.zip": { $gt: 10000 } })For multiple conditions on the same embedded object, use $elemMatch if it is an array of embedded docs.