Querying Nested Fields
What you'll learn: How to access and filter data inside nested objects and arrays in document databases.
Why Nested Fields Matter
Document databases like MongoDB store data as JSON-like structures where objects can contain other objects and arrays. Unlike relational tables with flat rows, a single document might have customer information with a nested address object, or an order document with an array of line items. You need specific syntax to reach into these nested structures to read or filter data.
Dot Notation for Nested Objects
To access fields inside nested objects, use dot notation with the parent and child field names separated by a period. Think of it like giving directions: "Go to the address object, then find the city field."
For example, if a document has this structure:
{
"name": "Alice",
"address": {
"city": "Portland",
"zip": "97201"
}
}
You'd query address.city to filter by city. The dot acts like a path through the nested hierarchy.
Array Operators
Arrays require special operators because they contain multiple values. You might want to:
- Check if an array contains a specific value
- Match documents where any array element meets a condition
- Filter by the size of an array
For instance, if an order document has an items array, you can query whether any item has a particular product code or whether the array has exactly 3 elements.
Combining Paths
You can combine dots to go deeper: order.items.0.price accesses the price of the first item in an array within an order object. Most document databases support filtering on these deep paths.
Key Takeaway: Dot notation provides a path-like syntax to query nested objects, while array operators let you match conditions within collections of values—essential skills for working with hierarchical document data.