nerdexam
MongoDB

C100DBA · Question #131

Consider the following document: > db.c.find() { "_id" : 12, b : [ 3, 5, 7, 2, 1, -4, 3, 12 ] } Which of the following queries on the "c" collection will return only the first five elements of the…

The correct answer is A. db.c.find( { > , { b : { $slice : [ 0 , 5 ] } } ). Option A is correct because MongoDB's $slice projection operator is specifically designed to limit array elements returned in query results - $slice: [0, 5] means "skip 0 elements, return 5," yielding [3, 5, 7, 2, 1] exactly as required. Why the distractors fail: B places [0…

MongoDB Fundamentals

Question

Consider the following document:

db.c.find() { "_id" : 12, b : [ 3, 5, 7, 2, 1, -4, 3, 12 ] } Which of the following queries on the "c" collection will return only the first five elements of the array in the "b" field? E.g., Document you want returned by your query:

{ "_id" : 12, "b" : [ 3, 5, 7, 2, 1 ] >

Options

  • Adb.c.find( { > , { b : { $slice : [ 0 , 5 ] } } )
  • Bdb.c.find( { b : [ 0 , 5 ] > )
  • Cdb.c.find( { > , { b : { $substr[ 0 , 5 ] > > )
  • Ddb.c.find( { > , { b : [ 0, 1, 2, 3, 4, 5 ] > )
  • Edb.c.find( { > , { b : [ 0 , 5 ] > )

How the community answered

(47 responses)
  • A
    77% (36)
  • B
    15% (7)
  • C
    6% (3)
  • D
    2% (1)

Explanation

Option A is correct because MongoDB's $slice projection operator is specifically designed to limit array elements returned in query results - $slice: [0, 5] means "skip 0 elements, return 5," yielding [3, 5, 7, 2, 1] exactly as required.

Why the distractors fail:

  • B places [0, 5] in the filter (match) position, which tries to match documents where b equals the array [0, 5] - it won't match anything and has no projection.
  • C uses $substr, which is a string operator, not an array operator - it doesn't exist in the context of array projection.
  • D uses a raw array [0, 1, 2, 3, 4, 5] in the projection, which is not valid MongoDB syntax for slicing.
  • E is similar to B's mistake - [0, 5] in the projection field value is not a recognized operator, so MongoDB won't know what to do with it.

Memory tip: Think of $slice like slicing bread - it's always paired with the $ sign (a projection operator), takes the form $slice: [skip, limit], and lives in the second argument (the projection document) of find(), never in the filter.

Topics

#$slice#array projection#query operators#field projection

Community Discussion

No community discussion yet for this question.

Full C100DBA Practice