Real-World Query Examples
E-commerce Product Listing Scenario
Retrieving Top-Selling Products
## Find top 5 best-selling products
db.products.find()
.sort({sales_count: -1})
.limit(5)
## First page of products (10 items per page)
db.products.find()
.skip(0)
.limit(10)
## Second page of products
db.products.find()
.skip(10)
.limit(10)
User Management Use Case
Finding Recent User Registrations
## Get 10 most recent user registrations
db.users.find()
.sort({registration_date: -1})
.limit(10)
## Find active users, sorted by last login
db.users.find({status: 'active'})
.sort({last_login: -1})
.skip(20)
.limit(10)
Data Analysis Scenarios
Sampling Large Datasets
## Random sample of 100 records
db.large_collection.find()
.limit(100)
Top N Analysis
## Top 5 highest-performing employees
db.employees.find()
.sort({performance_score: -1})
.limit(5)
Approach |
Pros |
Cons |
skip() /limit() |
Simple implementation |
Poor performance on large datasets |
Cursor-based |
Efficient for large collections |
More complex implementation |
Page Token |
Consistent results |
Requires additional metadata |
Complex Query Example
graph LR
A[Original Query] --> B[Apply Filters]
B --> C[Sort Results]
C --> D[Skip Documents]
D --> E[Limit Documents]
E --> F[Final Result Set]
Comprehensive Query Example
db.orders.find({
status: 'completed',
total_amount: {$gt: 100}
})
.sort({order_date: -1})
.skip(50)
.limit(10)
- Create appropriate indexes
- Avoid large
skip()
values
- Use projection to reduce document size
- Consider caching frequently accessed data
- Monitor query performance with explain()
Advanced Filtering with Limiting
Conditional Limiting
## Limit documents based on complex conditions
db.transactions.find({
amount: {$gt: 1000},
category: 'premium'
})
.limit(15)
Conclusion: Practical Limiting Strategies
- Always consider data volume
- Choose appropriate pagination method
- Balance between performance and data retrieval
- Test and optimize queries regularly