nerdexam
MongoDB

C100DBA · Question #88

What does the following $slice query return using the following command? db.posts.find( {}, { comments: { $slice: [ -10, 5 ] } } )

The correct answer is A. Returns 5 comments, beginning with the last 10 items. Option A is correct because $slice: [-10, 5] uses a two-element array where the first value is the skip offset and the second is the count to return. A negative first value counts from the end of the array, so -10 positions the cursor at the 10th-from-last element, and 5 returns

MongoDB Fundamentals

Question

What does the following $slice query return using the following command? db.posts.find( {}, { comments: { $slice: [ -10, 5 ] } } )

Options

  • AReturns 5 comments, beginning with the last 10 items
  • BReturns 10 comments, beginning with the last
  • CReturns 10 comments, beginning with the first
  • DReturns 5 comments, beginning with the first 10 items

How the community answered

(30 responses)
  • A
    83% (25)
  • B
    3% (1)
  • C
    10% (3)
  • D
    3% (1)

Explanation

Option A is correct because $slice: [-10, 5] uses a two-element array where the first value is the skip offset and the second is the count to return. A negative first value counts from the end of the array, so -10 positions the cursor at the 10th-from-last element, and 5 returns the next 5 elements from that point.

Why the distractors are wrong:

  • B confuses the two parameters - -10 is not a count of documents to return, it's a starting offset from the end.
  • C is doubly wrong: it misreads both the negative sign (which means "from the end," not "from the beginning") and the count.
  • D flips the semantics - 5 is not a skip amount and -10 is not a count; the roles of the two numbers are reversed.

Memory tip: Think of $slice: [skip, limit] like a window on an array. A negative skip slides the window from the tail of the array; a positive limit defines how wide the window is. So [-10, 5] = "start 10 from the end, grab 5."

Topics

#$slice#array projection#negative index#find projection

Community Discussion

No community discussion yet for this question.

Full C100DBA Practice