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:
- 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. - Conditional queries: Use the
db.collection.find(query, projection)method to query documents based on specified conditions. Thequeryparameter specifies the query conditions and can use comparison operators, logical operators, regular expressions, etc., while theprojectionparameter specifies the fields of the document to be returned in the result. - Range queries: Use comparison operators for range queries, such as
$gt,$gte,$lt,$lte, etc. - Regular expression queries: Use the
$regexoperator for regular expression queries, for exampledb.collection.find({field: {$regex: /pattern/}}). - 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. - Text search: Use the
db.collection.find({$text: {$search: "text"}})method for full-text search, returning documents containing the specified text. - Spatial queries: Use operators such as
$geoWithin,$near,$geoIntersectsto perform spatial queries, for example querying documents near a specified coordinate. - Pagination queries: Use the
skip()andlimit()methods for pagination queries. For example,db.collection.find().skip(10).limit(5)indicates starting from the 10th document and returning 5 documents. - Sorting queries: Use the
sort()method to sort query results. For example,db.collection.find().sort({field: 1})indicates sorting by thefieldfield in ascending order.
The above are the commonly used query methods in MongoDB. You can choose the corresponding method based on specific requirements.