Bird
Raised Fist0
MongoDBquery~20 mins

Attribute pattern for variable fields in MongoDB - Practice Problems & Coding Challenges

Choose your learning style10 modes available
Challenge - 5 Problems
🎖️
Attribute Pattern Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ query_result
intermediate
2:00remaining
Find documents with variable field names matching a pattern
Given a MongoDB collection products where some documents have fields like attr_color, attr_size, and others have different attr_* fields, which query returns all documents that have at least one field starting with attr_?
A{ $expr: { $gt: [ { $size: { $objectToArray: '$$ROOT' } }, 0 ] } }
B{ $or: [ { 'attr_*': { $exists: true } } ] }
C{ $expr: { $gt: [ { $size: { $filter: { input: { $objectToArray: '$$ROOT' }, cond: { $regexMatch: { input: '$$this.k', regex: '^attr_' } } } } }, 0 ] } }
D{ attr: { $regex: '^attr_' } }
Attempts:
2 left
💡 Hint
Use $objectToArray to convert fields to key-value pairs and filter keys by regex.
📝 Syntax
intermediate
1:30remaining
Identify the syntax error in a MongoDB query filtering variable fields
Which of the following MongoDB queries has a syntax error when trying to find documents with fields starting with data_?
Adb.collection.find({ $expr: { $gt: [ { $size: { $filter: { input: { $objectToArray: '$$ROOT' }, cond: { $regexMatch: { input: '$$this.k', regex: '^data_' } } } } }, 0 ] } })
Bdb.collection.find({ $expr: { $gt: [ { $size: { $filter: { input: { $objectToArray: '$ROOT' }, cond: { $regexMatch: { input: '$$this.k', regex: '^data_' } } } } }, 0 ] } })
C)} } ] 0 ,} } } } } '_atad^' :xeger ,'k.siht$$' :tupni { :hctaMxeger$ { :dnoc ,} 'TOOR$$' :yarrAoTtcejbo$ { :tupni { :retlif$ { :ezis$ { [ :tg$ { :rpxe$ {(dnif.noitcelloc.bd
Db.collection.find({ $expr: { $gt: [ { $size: { $filter: { input: { $objectToArray: '$$ROOT' }, cond: { $regexMatch: { input: '$$this.k', regex: '^data_' } } } } }, 0 ] } })
Attempts:
2 left
💡 Hint
Check the variable referencing the root document inside $objectToArray.
🧠 Conceptual
advanced
2:00remaining
Understanding attribute pattern matching in MongoDB documents
Why is it necessary to use $objectToArray and $filter to find documents with fields matching a pattern like attr_* in MongoDB?
ABecause $objectToArray converts values to keys, allowing regex matching on values instead of keys.
BBecause MongoDB automatically indexes all fields starting with 'attr_', so $objectToArray optimizes the query.
CBecause $filter can only be used on arrays, and documents are arrays by default in MongoDB.
DBecause MongoDB does not support querying field names directly with regex, so fields must be converted to array elements to filter keys.
Attempts:
2 left
💡 Hint
Think about how MongoDB stores documents and how queries work on field names.
❓ optimization
advanced
2:30remaining
Optimizing queries for variable attribute fields in MongoDB
Which approach is the most efficient to find documents with any field starting with meta_ in a large MongoDB collection?
AStore all variable fields inside a subdocument named 'meta' and query with dot notation like 'meta.field'.
BCreate a wildcard index on all fields and query with a regex on the field name.
CUse $objectToArray and $filter with $regexMatch inside an aggregation pipeline to filter documents.
DUse $where with JavaScript to iterate over fields and check if any field name starts with 'meta_'.
Attempts:
2 left
💡 Hint
Consider indexing and query performance on large collections.
🔧 Debug
expert
3:00remaining
Debugging a MongoDB query for variable attribute fields
A developer wrote this query to find documents with fields starting with 'info_': db.collection.find({ $expr: { $gt: [ { $size: { $filter: { input: { $objectToArray: '$$ROOT' }, cond: { $regexMatch: { input: '$$this.k', regex: '/^info_/' } } } } }, 0 ] } }) Why does this query return no results even though matching documents exist?
AThe regex pattern is incorrectly wrapped in slashes, causing it to be treated as a string literal.
BThe variable '$$this.k' is invalid and should be '$$this.key'.
CThe $filter input should be '$ROOT' instead of '$$ROOT'.
DThe $size operator cannot be used inside $expr.
Attempts:
2 left
💡 Hint
Check how regex patterns are specified in MongoDB aggregation expressions.

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