nerdexam
MongoDB

C100DBA · Question #87

Consider that our posts collection contains an array field called tags that contains tags that the user enters. { Which of the following commands will find all the posts that have been tagged as tutor

The correct answer is C. db.posts.find( { tags : "tutorial" } );. Option C works because MongoDB automatically searches within array fields when you query with a scalar value - { tags: "tutorial" } matches any document where "tutorial" appears anywhere in the tags array, without needing any special operator. Why the others fail: A uses ["tutori

MongoDB Fundamentals

Question

Consider that our posts collection contains an array field called tags that contains tags that the user enters. { Which of the following commands will find all the posts that have been tagged as tutorial.

Exhibit

C100DBA question #87 exhibit

Options

  • Adb.posts.find( { tags : ["tutorial"] } );
  • Bdb.posts.find( { $array : {tags: "tutorial") > );
  • Cdb.posts.find( { tags : "tutorial" } );
  • Ddb.posts.findInArray( { tags : "tutorial" > );

How the community answered

(39 responses)
  • A
    3% (1)
  • B
    3% (1)
  • C
    95% (37)

Explanation

Option C works because MongoDB automatically searches within array fields when you query with a scalar value - { tags: "tutorial" } matches any document where "tutorial" appears anywhere in the tags array, without needing any special operator.

Why the others fail:

  • A uses ["tutorial"] (an array literal), which only matches documents where tags is exactly ["tutorial"] with no other elements - far too restrictive.
  • B uses $array, which is not a real MongoDB operator - this will throw an error.
  • D uses findInArray(), which is not a real MongoDB method - the driver doesn't expose this function.

Memory tip: In MongoDB, "scalar matches array" - if you query a field with a single value, Mongo is smart enough to check inside arrays for you. You only need array-specific operators ($all, $elemMatch, $size) when your condition is more complex than a simple value match.

Topics

#array field query#find#array matching

Community Discussion

No community discussion yet for this question.

Full C100DBA Practice