MongoDB provides a rich and flexible Query API that allows you to interact with your data using various query operators and expressions. The MongoDB Query API is used to retrieve, filter, and manipulate data stored in MongoDB databases.
Basic Query Structure:
{ field: value }
db.collection_name
: Specifies the MongoDB collection you want to query.find(query_filter)
: Retrieves documents from the collection based on the specified query filter.
Query Operators:
MongoDB supports a wide range of query operators for building complex queries. Some commonly used operators include:
-
Equality:
{ field: value }
-
Inequality:
{ field: { $ne: value } }
-
Comparison:
{ field: { $gt: value } } { field: { $lt: value } }
-
Logical AND / OR:
{ $and: [{ condition1 }, { condition2 }] } { $or: [{ condition1 }, { condition2 }] }
-
Element Existence:
{ field: { $exists: true } }
-
Regular Expression:
{ field: { $regex: /pattern/i } }
Projection:
Use projection to limit the fields returned in the result set.
db.collection_name.find(query_filter, projection_fields);
Example:
db.users.find({}, { name: 1, email: 1, _id: 0 });
Sorting:
Use the sort()
method to sort the result set.
db.collection_name.find(query_filter).sort(sort_criteria);
Example:
db.users.find({}).sort({ age: 1 }); // Sort by age in ascending order db.users.find({}).sort({ name: -1 }); // Sort by name in descending order
Aggregation Pipeline:
The Aggregation Pipeline allows for more complex data transformations.
Example:
db.sales.aggregate([ { $match: { status: "completed" } }, { $group: { _id: "$product", total_sales: { $sum: "$amount" } } }, { $sort: { total_sales: -1 } } ]);
Indexing:
Create indexes to improve query performance.
db.collection_name.createIndex({ field: 1 });
Example:
db.users.createIndex({ email: 1 });
Full-Text Search:
MongoDB provides full-text search capabilities.
db.collection_name.find({ $text: { $search: "keyword" } });
Comments