Problem Statement
Given an employees collection with nested salary history and skills array, write queries to find employees with specific criteria and calculate aggregations.
Explanation
Working with complex document structures in MongoDB requires understanding nested field access, array queries, and aggregation pipelines. Let's explore practical query scenarios using an employees collection with embedded documents and arrays.
For querying nested fields, use dot notation to access fields within embedded documents. For example, to find employees in a specific city, query address.city. MongoDB treats embedded documents as regular fields once you use dot notation.
For array queries, MongoDB provides specialized operators. To find employees with a specific skill, use the array field directly and MongoDB matches if any element equals the value. For complex array conditions, use dollar elemMatch to ensure all conditions apply to the same array element.
For aggregation scenarios, use the aggregation pipeline to perform calculations across documents. The dollar group stage groups documents by fields and calculates aggregates using accumulator operators like dollar sum, dollar avg, dollar max, and dollar min.
For sorting by nested or computed fields, use dollar addFields to create temporary fields, then dollar sort on those fields. This is useful when sorting by array length or computed values.
For filtering arrays and projections, use dollar filter in aggregation pipelines to include only specific array elements in results. This is more powerful than projection alone because you can apply complex conditions.
For combining multiple conditions, use logical operators like dollar and, dollar or, and dollar not to build complex queries. Array operators like dollar all ensure arrays contain all specified values, while dollar in matches if the field equals any value in an array.
These techniques combine to enable sophisticated queries on complex document structures while maintaining query performance through proper indexing on query fields.