Bird
Raised Fist0
MongoDBquery~10 mins

Attribute pattern for variable fields in MongoDB - Step-by-Step Execution

Choose your learning style10 modes available
Concept Flow - Attribute pattern for variable fields
Start with collection
↓
Define attribute pattern
↓
Use $regex in query
↓
Match documents with variable fields
↓
Return matched documents
↓
End
This flow shows how to use a regex pattern to find documents with variable attribute values in MongoDB.
Execution Sample
MongoDB
db.collection.find({"fieldName": {$regex: /^prefix_\d+$/}})
Find documents where 'fieldName' matches a pattern like 'prefix_123'.
Execution Table
StepDocumentfieldName ValueRegex Match?Action
1{"fieldName": "prefix_1"}prefix_1YesInclude document
2{"fieldName": "prefix_123"}prefix_123YesInclude document
3{"fieldName": "prefix_abc"}prefix_abcNoExclude document
4{"fieldName": "other_123"}other_123NoExclude document
5{"fieldName": "prefix_4567"}prefix_4567YesInclude document
6No more documentsStop search
💡 No more documents to check, query ends.
Variable Tracker
VariableStartAfter 1After 2After 3After 4After 5Final
fieldNameprefix_1prefix_123prefix_abcother_123prefix_4567prefix_4567
Match ResultYesYesNoNoYesYes
Key Moments - 2 Insights
Why does 'prefix_abc' not match the regex pattern?
Because the regex /^prefix_\d+$/ expects digits after 'prefix_', but 'abc' are letters, so it fails (see execution_table row 3).
What happens when a document's fieldName does not start with 'prefix_'?
It does not match the regex and is excluded from results (see execution_table row 4).
Visual Quiz - 3 Questions
Test your understanding
Look at the execution_table, which document is included at step 2?
A{"fieldName": "prefix_abc"}
B{"fieldName": "prefix_123"}
C{"fieldName": "other_123"}
D{"fieldName": "prefix_4567"}
💡 Hint
Check the 'Document' and 'Action' columns at step 2 in execution_table.
At which step does the regex match fail because of letters instead of digits?
AStep 4
BStep 1
CStep 3
DStep 5
💡 Hint
Look at 'Regex Match?' column in execution_table for step 3.
If the regex was changed to /^prefix_\w+$/, which step's result would change?
AStep 3 would match
BStep 4 would match
CStep 1 would not match
DNo changes
💡 Hint
Consider that \w matches letters and digits, so 'prefix_abc' would match.
Concept Snapshot
MongoDB attribute pattern matching:
Use $regex in find queries to match variable field values.
Syntax: {field: {$regex: /pattern/}}
Example: /^prefix_\d+$/ matches 'prefix_' followed by digits.
Only documents with matching fields are returned.
Useful for flexible attribute names or values.
Full Transcript
This visual execution shows how MongoDB uses regex patterns to find documents with variable attribute values. Starting with a collection, we define a regex pattern to match field values like 'prefix_123'. The query checks each document's fieldName against the regex. Documents matching the pattern are included in results; others are excluded. The execution table traces each document's fieldName and whether it matches. Variable tracker shows how fieldName and match results change step by step. Key moments clarify why some values fail to match and how the regex works. The quiz tests understanding of matching steps and regex changes. This helps beginners see how MongoDB queries can flexibly find documents with variable fields.

Practice

(1/5)
1. In MongoDB, which operator helps you find documents where a field's value matches a text pattern?
easy
A. $match
B. $regex
C. $group
D. $project

Solution

  1. Step 1: Understand pattern matching in MongoDB

    MongoDB uses $regex to match string patterns inside field values.
  2. Step 2: Identify the operator for text pattern search

    $regex is the operator designed for regular expression matching in queries.
  3. Final Answer:

    $regex -> Option B
  4. Quick Check:

    Pattern matching = $regex [OK]
Hint: Use $regex to match text patterns in fields quickly [OK]
Common Mistakes:
  • Confusing $regex with $match which filters documents
  • Using $group which aggregates data, not filters by pattern
  • Using $project which reshapes documents, not filters
2. Which MongoDB aggregation stage converts a document's fields into an array of key-value pairs, useful for filtering variable field names?
easy
A. $objectToArray
B. $filter
C. $arrayToObject
D. $match

Solution

  1. Step 1: Understand field-to-array conversion

    $objectToArray converts document fields into an array of {k, v} pairs.
  2. Step 2: Identify the correct stage for this conversion

    $objectToArray is the aggregation operator that does this transformation.
  3. Final Answer:

    $objectToArray -> Option A
  4. Quick Check:

    Field to array = $objectToArray [OK]
Hint: Use $objectToArray to turn fields into key-value arrays [OK]
Common Mistakes:
  • Using $filter which filters arrays but doesn't convert fields
  • Confusing $arrayToObject which does the reverse conversion
  • Using $match which filters documents, not fields
3. Given this aggregation pipeline snippet, what will be the output for a document {"a1": 5, "b2": 10, "c3": 15}?
{
  $project: {
    filteredFields: {
      $filter: {
        input: { $objectToArray: "$ROOT" },
        as: "field",
        cond: { $regexMatch: { input: "$$field.k", regex: /^a/ } }
      }
    }
  }
}
medium
A. {"filteredFields": [{"k": "a1", "v": 5}]}
B. {"filteredFields": [{"k": "b2", "v": 10}]}
C. {"filteredFields": [{"k": "c3", "v": 15}]}
D. {"filteredFields": []}

Solution

  1. Step 1: Convert document fields to array

    $objectToArray converts {"a1":5,"b2":10,"c3":15} to [{k:"a1",v:5},{k:"b2",v:10},{k:"c3",v:15}].
  2. Step 2: Filter keys starting with 'a'

    $filter with regex /^a/ keeps only fields where key starts with 'a', so only {k:"a1",v:5} remains.
  3. Final Answer:

    {"filteredFields": [{"k": "a1", "v": 5}]} -> Option A
  4. Quick Check:

    Filter keys /^a/ = only "a1" field [OK]
Hint: Filter keys with $regexMatch inside $filter after $objectToArray [OK]
Common Mistakes:
  • Forgetting to convert fields to array before filtering
  • Using wrong regex pattern or syntax
  • Expecting all fields instead of filtered ones
4. Identify the error in this aggregation stage that tries to filter fields with names containing 'score':
{
  $project: {
    scores: {
      $filter: {
        input: { $objectToArray: "$ROOT" },
        as: "field",
        cond: { $regex: "score", input: "$$field.k" }
      }
    }
  }
}
medium
A. Incorrect order of $regex arguments; 'input' must come first
B. Missing $match stage before $project
C. Using $regex instead of $regexMatch inside $filter condition
D. Cannot use $objectToArray on $ROOT

Solution

  1. Step 1: Check $regex usage inside $filter cond

    $regex is a query operator, but inside aggregation expressions, $regexMatch must be used for regex matching.
  2. Step 2: Identify correct regex function for aggregation

    Use $regexMatch with 'input' and 'regex' keys; $regex alone is invalid here.
  3. Final Answer:

    Using $regex instead of $regexMatch inside $filter condition -> Option C
  4. Quick Check:

    Aggregation regex = $regexMatch, not $regex [OK]
Hint: Use $regexMatch, not $regex, inside aggregation expressions [OK]
Common Mistakes:
  • Swapping input and regex keys in $regexMatch
  • Trying to use $regex query operator inside aggregation
  • Assuming $objectToArray can't be used on $ROOT
5. You have documents with variable field names like "score_math", "score_science", "age", "name". How do you write an aggregation pipeline stage to create a new field "scores" containing only fields whose names start with "score_" and their values?
hard
A. { $project: { scores: { $objectToArray: "$ROOT" } } }
B. { $match: { scores: { $regex: /^score_/ } } }
C. { $project: { scores: { $filter: { input: "$ROOT", as: "f", cond: { $regexMatch: { input: "$$f.k", regex: /^score_/ } } } } } }
D. { $project: { scores: { $arrayToObject: { $filter: { input: { $objectToArray: "$ROOT" }, as: "f", cond: { $regexMatch: { input: "$$f.k", regex: /^score_/ } } } } } } }

Solution

  1. Step 1: Convert document fields to array for filtering

    Use $objectToArray on "$ROOT" to get array of key-value pairs.
  2. Step 2: Filter keys starting with "score_" using $filter and $regexMatch

    Apply $filter with condition $regexMatch on keys matching /^score_/.
  3. Step 3: Convert filtered array back to object

    Use $arrayToObject to convert filtered array back to an object with only score fields.
  4. Final Answer:

    { $project: { scores: { $arrayToObject: { $filter: { input: { $objectToArray: "$ROOT" }, as: "f", cond: { $regexMatch: { input: "$$f.k", regex: /^score_/ } } } } } } } -> Option D
  5. Quick Check:

    Filter keys + convert back = { $project: { scores: { $arrayToObject: { $filter: { input: { $objectToArray: "$ROOT" }, as: "f", cond: { $regexMatch: { input: "$$f.k", regex: /^score_/ } } } } } } } [OK]
Hint: Convert fields to array, filter keys, then convert back to object [OK]
Common Mistakes:
  • Trying to filter directly on $ROOT without conversion
  • Using $match instead of $project for field transformation
  • Not converting filtered array back to object with $arrayToObject
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard