MongoDB: Querying Documents
Subject: nodejs
MongoDB: Querying Documents
Querying documents in MongoDB retrieves data from a collection by specifying conditions that the documents must satisfy. This flexible process supports complex searches using various operators.
Why Query Documents?
- Targeted Retrieval: Fetch only the data you need.
- Filtering and Analytics: Analyze subsets of your data.
- Search and Filtering Features: Power dynamic applications.
- Trend Analysis: Use queries to identify patterns or outliers.
Core Concepts
- Query Document (Filter): A JavaScript object specifying match conditions. Example:
{ age: { $gt: 20 } }. - Query Operators: Keywords (like
$gt,$in) used to create expressive filters. - Projection: Specifies which fields to return (e.g.,
{ name: 1, _id: 0 }).
Basic Query Syntax
Common Query Operators
Comparison:
$eq,$ne: Equal, Not equal$gt,$gte: Greater than / equal$lt,$lte: Less than / equal$in,$nin: Matches values in / not in an array
Logical:
$and,$or,$not,$nor: Combine multiple conditions
Element:
$exists: Field presence$type: Match by BSON type
Evaluation:
$regex: Regular expression pattern matching$where: JavaScript-based conditions (less performant)
Array:
$all: Matches arrays with all specified values$size: Match array length$elemMatch: Match documents based on array elements
Text Search:
$text: Full-text search (requires index)
Geo:
$near,$geoWithin: Spatial queries (not covered in detail here)
Node.js Examples: Advanced Queries
Prerequisites: MongoDB running, Node.js installed, npm install mongodb
Assume a users collection contains:
1. Using $gt, $lte, $and (age range & status)
Expected Output:
2. Using $all and $or
Expected Output:
3. Using $exists and $regex
Expected Output:
Key Takeaways
- MongoDB's query syntax supports expressive and powerful filtering.
- Operators like
$gt,$and,$all, and$regexallow for nuanced searches. - Projection optimizes output by limiting returned fields.
- Queries are executed through
.find()or.findOne()using structured filters and projection documents.