C100DBA practice question 9 of 25

Which of the following operator can be used to control the number of items of an array that a query returns?

Full set: 130 questions
Answer options
A: $ elemMatch
B: $slice Correct answer
C: $
D: MongoDB does not support partial retrieval of items from an array
Correct Answer:
B. $slice
Explanation

The $slice projection operator is specifically designed to control the number of elements returned from an array field in a query result. It can be used to return the first n elements, the last n elements, or a specific subset of elements from the array by specifying a number of elements to skip and a number to return. This provides precise control over which part of an array is included in the output documents, which is useful for managing large arrays or for pagination.

Why Incorrect

A. The $elemMatch projection operator returns only the first element in an array that matches the specified condition, not a configurable number of items.
C. The $ positional projection operator returns only the first array element that matches the query condition, similar to $elemMatch but with a different syntax.
D. This statement is false. MongoDB provides several operators, most notably $slice, for retrieving partial array content.

References

1. MongoDB Manual, Projection Operators, $slice. "The $slice projection operator specifies the number of elements in an array to return in the query result." The documentation provides examples for returning the first n, last n, and a sub-section of an array.

2. MongoDB Manual, Projection Operators, $elemMatch (projection). "The $elemMatch operator projects the first element in an array that matches the specified $elemMatch condition."

3. MongoDB Manual, Projection Operators, $ (projection). "The positional $ operator limits the contents of an to return the first element that matches the query condition on the array."

Scroll to Top