Mongodb Certified Developer Associate C100dev · Free Practice Question Medium

Question 39

In your database a movies collection is given where each document has the following structure:



Which of the following queries will return all movies that are in the Fantasy and Drama (both) genre?

  • A

    db.movies.find( { genres: { $size: ['Fantasy', 'Drama'] } } )

  • B

    db.movies.find( { genres: { $in: ['Fantasy', 'Drama'] } } )

  • C

    db.movies.find( { genres: { $all: ['Fantasy', 'Drama'] } } )

  • D

    db.movies.find( { genres: { $elemMatch: ['Fantasy', 'Drama'] } } )

Reveal correct answer

Correct answer: C

A.

The $size operator in MongoDB is used to match documents where the size of the array field matches the specified value. In this case, the query is looking for documents where the "genres" field has a size of exactly 2 with values ['Fantasy', 'Drama']. This query will not give the desired result as it checks for the size of the array, not the values within the array.

B.

The $in operator in MongoDB is used to match documents where the field contains any of the specified values in the array. In this case, the query is looking for documents where the "genres" field contains either "Fantasy" or "Drama" genres. This query will not return movies that are in both genres.

C.

The $all operator in MongoDB is used to match documents where the field contains all the specified values in the array. In this case, the query is looking for documents where the "genres" field contains both "Fantasy" and "Drama" genres. Therefore, it will return all movies that are in the Fantasy and Drama (both) genre.

D.

The $elemMatch operator in MongoDB is used to match documents where at least one element in the array field matches all the specified conditions. In this case, the query is looking for documents where the "genres" field has an element that matches both 'Fantasy' and 'Drama', but it is not the correct usage of $elemMatch. The correct usage of $elemMatch involves specifying conditions for different fields within the element. This query will not give the desired result.

Discussion

Think the marked answer is wrong, or have a better explanation? Share it below — comments appear after review.

You must be logged in to post a comment.

Preparing For

Your Certification?

255+ certifications
Detailed explanations
Free PDF samples

Has All The Questions You Need