Skip to main content

Archive

Show more

MongoDB Query Operators

MongoDB: Query Operators

  • Query operators in MongoDB are powerful tools for filtering and retrieving data from collections based on specific criteria.
  • This tutorial will cover various query operators supported by MongoDB, providing examples for each scenario.

1. Comparison Operators

Comparison operators allow you to compare field values with specified expressions.

Examples:

  • $eq: Matches values that are equal to a specified value.
  • $ne: Matches values that are not equal to a specified value.
  • $gt: Matches values that are greater than a specified value.
  • $lt: Matches values that are less than a specified value.
  • $gte: Matches values that are greater than or equal to a specified value.
  • $lte: Matches values that are less than or equal to a specified value.

2. Logical Operators

Logical operators perform logical operations on expressions and return true or false.

Examples:

  • $and: Joins query clauses with a logical AND.
  • $or: Joins query clauses with a logical OR.
  • $not: Inverts the effect of a query expression.
  • $nor: Joins query clauses with a logical NOR.

3. Element Operators

Element operators test for the existence of fields or elements within a document.

Examples:

  • $exists: Matches documents that contain the specified field.
  • $type: Matches documents that have the specified type.

4. Array Operators

Array operators perform operations on arrays, such as querying for array elements.

Examples:

  • $elemMatch: Matches documents that contain an array field with at least one element that matches all the specified query criteria.
  • $size: Matches documents that contain an array field with a specific number of elements.

5. Evaluation Operators

Evaluation operators perform specific evaluations within a query.

Examples:

  • $regex: Selects documents where values match a specified regular expression.
  • $text: Performs a text search on the content of the fields indexed with a text index.
  • $where: Matches documents that satisfy a JavaScript expression.

6. Geospatial Operators

Geospatial operators allow you to perform queries on geospatial data.

Examples:

  • $geoNear: Returns documents based on proximity to a geospatial point.
  • $geoWithin: Returns documents that are within a specified shape.
  • $geoIntersects: Returns documents that intersect with a specified geometry.

7. Bitwise Operators

Bitwise operators perform bitwise operations on integer values.

Examples:

  • $bit: Performs bitwise AND, OR, and XOR operations on integer values.

8. What's Next?

Now that you've familiarized yourself with MongoDB query operators, you're equipped to construct sophisticated queries to retrieve specific data from your MongoDB collections.

Continue exploring advanced MongoDB topics such as indexing, aggregation, and database management to enhance your MongoDB skills further.

Comments