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
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)- A83% (25)
- B3% (1)
- C10% (3)
- D3% (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 -
-10is 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 -
5is not a skip amount and-10is 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
Community Discussion
No community discussion yet for this question.