How to Query Arrays in MongoDB

Introduction

In this article we’ll be talking about how to query arrays in MongoDB. This is an extremely common practice and you’ll want to have it down cold if you’re working with MongoDB frequently. We’ll go over several examples and scenarios and you should follow along with your own data as much as you can because the concepts will sink in better if you actually use the commands we present.

Prerequisites

  • You should have MongoDB installed and running
    • You can do this with a mongod command if you have installed MongoDB
  • You should have access to the MongoDB command line
    • You can get access to the command line be executing the mongo command while MongoDB is running.
  • Although it’s not required it’s helpful to brush up on regular expression syntax because it can be intimidating if you don’t have a basic understanding in place.

How to Query Arrays in MongoDB

First we’ll go over the most common situation in querying arrays, checking to see if an item exists in an array. Let’s assume we have a document that looks like this in our grocerydb in our products collection:

{
  "name": "Hersheys Almond"
  "ingredients": [
    "Cacoa",
    "Almond",
    "Sugar"
  ]
}

Find a single element in an Array

If you wanted to find products with the ingredients “Almonds” you could do this search:

db.products.find({ingredients : "Almond"})

This query will match the above document.

FInd multiple elements in an Array

Another common scenario would be to query for documents that have multiple items in an array. For this you’ll need to use the $all operator. To use the previous example again we could query the document by using the query:

db.products.find({ingredients : {$all : ["Almond", "Sugar"]}})

This too will return the “Hershey’s Almond” product because it has BOTH “Almond” and “Sugar” in the ingredients list. In this query it must have both to match the query.

It’s important to note here that order doesn’t matter with the $all operator. As long as the array field contains both elements it will match the query.

Find an Array that Matches Exactly

Another common scenario would be to query for documents with an exact match to a given array. This would be accomplished like so:

db.products.find({ingredients : ["Cacao", "Almond", "Sugar"]}})

Match on Specific Index in an Array

Let’s say you had an array field that was ordered in some way and you wanted to check that the third element in the array was a certain value. This query is a little less intuitive so let’s see an example of this situation, we will query our product by looking for products where the 3rd element in the Array is “Sugar”:

db.products.find({"ingredients.2" : "Sugar"})

From this query you can probably guess that arrays have a 0-based index, so the first element is index 0, the second element index is 1, and the third element index is 2. As you can see we wrapped the field name in quotes and added “.2” to specify that we want to check the third element ( index = 2) for the value “Sugar”.

Find an Array by It’s Length

Another common desire is to find documents that have an array of a certain length. For example if you were a health conscious grocery store owner who preferred raw foods, you might query your products by the number of ingredients.

To do this type of query you’d use the $size operator. Let’s see an example of this query to query products with only three ingredients:

db.products.find({ingredients : {"$size" : 3}})

Conclusion

We have covered what we think are some of the most common types of queries made on array fields. This isn’t an exhaustive list by any means but we hope that it answered some of your questions or at least gave you a good starting point. If you have any questions about MongoDB don’t hesitate to reach out to us at Object Rocket, we are here to help.

Pilot the ObjectRocket Platform Free!

Try Fully-Managed Redis,
MongoDB & Elasticsearch

Get Started

OR

Try CockroachDB
in Beta

Get Started

Keep in the know!

Subscribe to our emails and we’ll let you know what’s going on at ObjectRocket. We hate spam and make it easy to unsubscribe.