Course contentsShow
← Databases & SQL
Lesson 1191 of 1,95311. NoSQL and Document ModelsFree lesson

Querying Nested Arrays

Apply predicate filters specifically designed for sub-document elements.

In this lesson, you will learn how to precisely target documents by applying predicate filters to specific elements stored within nested arrays.

When moving from a relational model to a document-oriented structure, we often store related data inside arrays rather than separate tables. For example, imagine a users collection where each document contains an array of orders objects. If you want to find all users who purchased a specific item, you cannot simply query the array field; you must understand how to filter the contents of that array.

Applying Predicates to Nested Elements

When you query an array, the database engine inspects the elements individually. If you provide a criteria for a nested object, the engine checks if any element within that array satisfies the condition.

Consider this document structure:

{
  "username": "jdoe",
  "orders": [
    { "item": "laptop", "status": "shipped" },
    { "item": "mouse", "status": "delivered" }
  ]
}

If you want to find users who have a "shipped" order, you apply a predicate filter directly to the nested field path. Using dot notation, you target the sub-document element:

SELECT * FROM users 
WHERE orders.status = 'shipped';

The Nuance of Multi-Field Filters

A common mistake occurs when filtering by multiple fields within the same nested object. If you query for orders.item = 'laptop' AND orders.status = 'delivered', a standard document query might return the document above, even though the "laptop" order is "shipped" and the "delivered" order is for a "mouse." The engine sees that the document contains a "laptop" and a "delivered" order, fulfilling both conditions independently.

To enforce that both conditions apply to the same sub-document, you must use an "elemMatch" style operator (or its SQL equivalent provided by your specific document engine), which forces the filter to evaluate the predicate against individual array elements rather than the array as a whole.

Mastering these filters allows you to traverse deeply nested structures without needing to "flatten" your data, keeping your document design efficient for read-heavy workloads.

Key Takeaway: When querying nested arrays, use dot notation to reach sub-document fields, but use specialized element-matching operators to ensure multiple predicates apply to the same specific array element.