C100DBA · Question #22
Consider the following posts document: Which of the following queries will return the documents but with only the first two tags in the tags array?
The correct answer is D. db.posts.find({author:"Tom">,{tags:{$slice:2»). Option D is correct because $slice is a projection operator used in the second argument of find() to limit the number of array elements returned - {tags:{$slice:2}} tells MongoDB to return only the first two elements of the tags array. Option A misuses .limit(), which is a…
Question
Consider the following posts document:
Which of the following queries will return the documents but with only the first two tags in the tags array?
Exhibit
Options
- Adb.posts.find({author:"Tom"».limit({tags:2})
- Bdb.posts.find({author:"Tom"».limit($slice:{tags:2>)
- Ddb.posts.find({author:"Tom">,{tags:{$slice:2»)
How the community answered
(49 responses)- A16% (8)
- B8% (4)
- D76% (37)
Explanation
Option D is correct because $slice is a projection operator used in the second argument of find() to limit the number of array elements returned - {tags:{$slice:2}} tells MongoDB to return only the first two elements of the tags array. Option A misuses .limit(), which is a cursor method that restricts the number of documents returned, not array elements, and passes it a field-count object which is invalid syntax. Option B makes the same conceptual mistake by trying to pass $slice inside .limit(), which has no understanding of $slice whatsoever. A helpful memory tip: think of the two arguments to find() as filter, then fields - the first {} selects which documents, the second {} controls which fields and how much of them, and $slice lives in that second "how much" argument alongside other projection operators.
Topics
Community Discussion
No community discussion yet for this question.
