From the course: MongoDB Node.js Developer Associate Cert Prep

Querying on array elements in MongoDB

- Welcome. In this video, you'll learn how to query your MongoDB database for specific values, also called "elements," within an array. First, we'll go over how to query arrays in documents. Then, we'll create a query by using the "$elemMatch" operator to find documents in an array that match specific query criteria. Let's begin with a common use case for querying arrays in MongoDB, searching for every document with a fields that contains the value we specify. For instance, here we have a collection named "accounts". Each document in this collection has a field named "products". Let's examine a query to find all documents that contain the value of "InvestmentStock". The syntax may look familiar if you've used equality match before. This is because the query is looking for a products field that has a value equal to "InvestmentStock" or a products field with an array containing an element equal to "InvestmentStock". After we run the query, the result provided to us is all documents that have a products field with either an array or a scaler value containing "InvestmentStock". The query doesn't return any documents that don't contain that value. What if you want to query for a value or values, but only return a match when they're an element of an array? In these situations, we can use the "$elemMatch" operator. To do this, we need to use "$elemMatch" along with the "$eq" operator. This ensures that the products field is an array that contains "InvestmentStock". Now, all of the documents returned have a products field that's an array with an element equal to "InvestmentStock". We can also use "$elemMatch" to find documents where a single array element matches multiple query criteria. We place each query criteria in "$elemMatch" separated by a comma. In this example, we'll use a collection called "sales," and we'll focus on the items field. This field contains an array of sub documents with the item's information. This query will find all documents with at least one item from the sales collection that's a laptop with a price greater than $800 and with a quantity greater than or equal to one. After we run this query, the documents returned will contain laptops with quantities greater than one and prices greater than 800. Let's recap the key points covered in this video. First, we queried arrays in a document. Then, we used "$elemMatch" to find a sub document that matches specific criteria in an array.

Contents