MongoDB Query Basic Concepts

MongoDB is a document-oriented database that supports rich query syntax, enabling users to flexibly query documents based on their content, structure, and metadata. Below are the commonly used query methods in MongoDB:

  1. Find all documents: Use the db.collection.find() method to find all documents in a collection (collection). This method returns a cursor object, which can be iterated to access all documents.
  2. Conditional queries: Use the db.collection.find(query, projection) method to query documents based on specified conditions. The query parameter specifies the query conditions and can use comparison operators, logical operators, regular expressions, etc., while the projection parameter specifies the fields of the document to be returned in the result.
  3. Range queries: Use comparison operators for range queries, such as $gt, $gte, $lt, $lte, etc.
  4. Regular expression queries: Use the $regex operator for regular expression queries, for example db.collection.find({field: {$regex: /pattern/}}).
  5. Aggregation queries: Use the db.collection.aggregate(pipeline) method to perform aggregation queries. This allows grouping, sorting, filtering operations on documents and returns calculated results.
  6. Text search: Use the db.collection.find({$text: {$search: "text"}}) method for full-text search, returning documents containing the specified text.
  7. Spatial queries: Use operators such as $geoWithin, $near, $geoIntersects to perform spatial queries, for example querying documents near a specified coordinate.
  8. Pagination queries: Use the skip() and limit() methods for pagination queries. For example, db.collection.find().skip(10).limit(5) indicates starting from the 10th document and returning 5 documents.
  9. Sorting queries: Use the sort() method to sort query results. For example, db.collection.find().sort({field: 1}) indicates sorting by the field field in ascending order.

The above are the commonly used query methods in MongoDB. You can choose the corresponding method based on specific requirements.