Query Arrays and Nested Documents
In Chapter 2, Documents and Data Types, we learned that MongoDB documents support complex object structures such as arrays, nested objects, arrays of objects, and more. The arrays and nested documents help store self-contained information. It is extremely important to have a mechanism to easily search for and retrieve the information stored in such complex structures. The MongoDB query language allows us to query such complex structures in the most intuitive manner. First, we will learn how to run queries on the array elements, and then we will learn how to run them on nested object fields.
Finding an Array by an Element
Querying over an array is similar to querying any other field. In the movies
collection, there are several arrays, and the cast
field is one of them. Consider that, in your movies service, the user wants to find movies starring the actor Charles Chaplin
. To create the query for this search, use an equality check on the field...