nerdexam
MongoDB

C100DBA · Question #36

Given a collection posts as shown below having a document array comments, which of the following command will create an index on the comment author descending?

The correct answer is C. db.posts.createIndex({comments.author":-l}). Option C is correct because MongoDB uses simple dot notation ("comments.author") to index fields inside arrays of embedded documents - when you index an array field this way, MongoDB automatically creates a multikey index that indexes every author value across all comment…

Performance Tuning

Question

Given a collection posts as shown below having a document array comments, which of the following command will create an index on the comment author descending?

Exhibit

C100DBA question #36 exhibit

Options

  • Adb.posts.createIndex({commerits.$.author":-l});
  • Bdb.posts.createIndex({comments.$.author": {$desc:l>});
  • Cdb.posts.createIndex({comments.author":-l});

How the community answered

(50 responses)
  • A
    4% (2)
  • B
    12% (6)
  • C
    84% (42)

Explanation

Option C is correct because MongoDB uses simple dot notation ("comments.author") to index fields inside arrays of embedded documents - when you index an array field this way, MongoDB automatically creates a multikey index that indexes every author value across all comment subdocuments, and -1 correctly specifies descending order.

Option A is wrong because the positional operator $ (used as comments.$.author) is only valid in query/update operations to reference a matched array element - it has no meaning in createIndex and will produce an error.

Option B is wrong for two reasons: it incorrectly uses the $ positional operator (same problem as A), and $desc is not a real MongoDB operator - index direction is specified purely as 1 (ascending) or -1 (descending), never with a keyword like $desc.

Memory tip: Think of indexing array subdocuments as "just dot notation, no drama" - "array.field": -1. No $, no keywords, just the path and the direction number.

Topics

#index creation#array index#nested documents#descending index

Community Discussion

No community discussion yet for this question.

Full C100DBA Practice