MongoDB Query Operators

MongoDB query operators let you filter on more than simple equality. They start with a dollar sign and go inside the filter document, for example { price: { $gt: 10 } } means "price greater than 10".

Comparison Operators

  • $eq equal, $ne not equal
  • $gt greater than, $gte greater or equal
  • $lt less than, $lte less or equal
  • $in matches any value in an array, $nin none of them

Ranges with $gte and $lte

Combine operators on the same field to build a range.

db.products.find(
  { price: { $gte: 8, $lte: 15 } },
  { _id: 0, name: 1, price: 1 }
).sort({ price: 1 })
[
  { name: 'Honey', price: 11.5 },
  { name: 'Basmati Rice', price: 12.5 },
  { name: 'Almonds', price: 15 }
]

$in and $nin

$in is like SQL IN.

db.products.find(
  { category: { $in: ["Oils", "Sweeteners"] } },
  { _id: 0, name: 1, category: 1 }
)
[
  { name: 'Olive Oil', category: 'Oils' },
  { name: 'Honey', category: 'Sweeteners' }
]

Logical Operators $or and $and

Fields listed together in a filter are already ANDed. Use $or for alternatives.

db.products.find(
  { $or: [ { stock: 0 }, { price: { $gt: 20 } } ] },
  { _id: 0, name: 1, price: 1, stock: 1 }
)
[
  { name: 'Coffee Beans', price: 22, stock: 80 },
  { name: 'Honey', price: 11.5, stock: 0 }
]

$exists and $regex

$exists checks whether a field is present; $regex matches text patterns. A case-insensitive regex uses the i option.

db.products.find({ tags: { $exists: true } }, { _id: 0, name: 1 })
db.products.find({ name: { $regex: "^c", $options: "i" } }, { _id: 0, name: 1 })
[ { name: 'Basmati Rice' }, { name: 'Almonds' } ]
[ { name: 'Coffee Beans' } ]

$elemMatch for Arrays of Objects

$elemMatch requires one array element to satisfy all conditions at once, which matters for arrays of sub-documents like order items.

db.orders.find({
  items: { $elemMatch: { product: "Green Tea", qty: { $gte: 20 } } }
}, { _id: 0, orderNo: 1 })
[ { orderNo: 102 } ]

Frequently asked questions

How do I write a NOT EQUAL query in MongoDB?

Use $ne: db.products.find({ category: { $ne: "Snacks" } }). Note that $ne also matches documents where the field does not exist.

When do I need $and explicitly?

Only when you need two conditions on the same field or operator, for example two $or groups. Otherwise listing fields together already means AND.

Are MongoDB regex queries slow?

A case-sensitive regex anchored with ^ can use an index. Unanchored or case-insensitive regexes scan many documents; use Atlas Search or a text index for real search.