Filter Array Elements in MongoDB

Have a Database Problem? Speak with an Expert for Free
Get Started >>

Introduction

If you’re using MongoDB to store and manage your data, you’ve probably noticed the database’s flexible document structure. In MongoDB, a field can have an array as a value. When you construct a MongoDB query, you may want to refine your results, filtering an array to return only specific elements. Fortunately, it’s easy to accomplish this with the help of the $filter operator. In this article, we’ll show you how to filter array elements in MongoDB and look at some simple examples to demonstrate how it’s done.

Prerequisite

Before proceeding with this tutorial, be sure that you’ve installed and configured the following:

Sample Dataset

We’ll need some sample data to use in our examples. Let’s take a look at the documents in our sample hardware collection:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
{
        "_id" : ObjectId("5e9662f3e4d449ab15e94881"),
        "sku" : 1001,
        "type" : "Graphic Card",
        "model" : "GTX-1660",
        "maker" : "MSI",
        "specification" : [
                {
                        "architecture" : "turing"
                },
                {
                        "boost_clock" : "1770 Mhz"
                },
                {
                        "frame_buffer" : "6 GB GDDR6"
                },
                {
                        "memory_speed" : "12 Gbps"
                }
        ],
        "review" : [
                {
                        "name" : "jason bouse",
                        "star" : 5,
                        "review" : "smooth gaming experience"
                },
                {
                        "name" : "ray stern",
                        "star" : 5,
                        "review" : "value for money"
                }
        ]
}
{
        "_id" : ObjectId("5e9662f3e4d449ab15e94882"),
        "sku" : 1002,
        "type" : "Graphic Card",
        "model" : "GTX-1060 Super",
        "maker" : "GIGABYTE",
        "specification" : [
                {
                        "architecture" : "turing"
                },
                {
                        "boost_clock" : "1830 Mhz"
                },
                {
                        "frame_buffer" : "6 GB GDDR6"
                },
                {
                        "memory_speed" : "336 Gbps"
                }
        ],
        "review" : [
                {
                        "name" : "dwane speed",
                        "star" : 5,
                        "review" : "rock solid graphic performance"
                },
                {
                        "name" : "michael bay",
                        "star" : 5,
                        "review" : "superb graphic rendering"
                }
        ]
}
{
        "_id" : ObjectId("5e9662f3e4d449ab15e94883"),
        "sku" : 1003,
        "type" : "Graphic Card",
        "model" : "GTX-1060 OC",
        "maker" : "ASUS",
        "specification" : [
                {
                        "architecture" : "turing"
                },
                {
                        "boost_clock" : "1809 Mhz"
                },
                {
                        "frame_buffer" : "6 GB GDDR6"
                },
                {
                        "memory_speed" : "336 Gbps"
                }
        ],
        "review" : [
                {
                        "name" : "igor redvlod",
                        "star" : 5,
                        "review" : "nice"
                },
                {
                        "name" : "Singh patel",
                        "star" : 4,
                        "review" : "interestingly good performance"
                }
        ]
}

You may want to create a MongoDB collection containing these documents so that you can follow along with our examples.

Filter MongoDB Array Element Using $Filter Operator

The $filter operator allows us to further refine the results of a MongoDB query.

This operator uses three variables:

  1. input – This represents the array that we want to extract.
  2. cond – This represents the set of conditions that must be met.
  3. as – This optional field contains a name for the variable that represent each element of the input array.

Here’s an example of how we can use the $filter operator:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
db.component.aggregate([
{
   "$match" : {
       "specification" : {
          "$elemMatch" : {
             "$and" : [
                { "frame_buffer" : "6 GB GDDR6" }
             ]
          }
       },
   }
},
{
   "$project" : {
       "sku" : 1, "maker" : 1,
       "specification" : {
          "$filter" : {
             "input" : "$specification",
             "as" : "specification",
             "cond" : {
                "$and" : [
                   { "$eq" : [ "$$specification.frame_buffer", "6 GB GDDR6" ] }
                ]
             }
          }
       }
   }
}
]).pretty();

The aggregate operation shown above filters the returned documents by including only the sku and maker fields and one element from the specification field.

The result should look like this:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
{
        "_id" : ObjectId("5e9667164d513751c0000a4d"),
        "sku" : 1001,
        "maker" : "MSI",
        "specification" : [
                {
                        "frame_buffer" : "6 GB GDDR6"
                }
        ]
}
{
        "_id" : ObjectId("5e9667164d513751c0000a4e"),
        "sku" : 1002,
        "maker" : "GIGABYTE",
        "specification" : [
                {
                        "frame_buffer" : "6 GB GDDR6"
                }
        ]
}
{
        "_id" : ObjectId("5e9667164d513751c0000a4f"),
        "sku" : 1003,
        "maker" : "ASUS",
        "specification" : [
                {
                        "frame_buffer" : "6 GB GDDR6"
                }
        ]
}

Filter MongoDB Array Element Using $Elematch Operator

Now that we understand how to use the $filter operator, let’s look at another way we can filter array elements. We will use another filter operator called $elematch, combined with the find() function:

1
2
3
db.component.find(
  { specification : { $elemMatch : { memory_speed : "336 Gbps"} } }
).pretty();

The command shown above filters the result by showing only documents where the specification array field has an element of memory_speed equal to 336 Gbps.

NOTE: The .pretty() function is used to indent the JSON document response, making the presentation of the document more readable.

The output should look like this:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
{
        "_id" : ObjectId("5e9667164d513751c0000a4e"),
        "sku" : 1002,
        "type" : "Graphic Card",
        "model" : "GTX-1060 Super",
        "maker" : "GIGABYTE",
        "specification" : [
                {
                        "architecture" : "turing"
                },
                {
                        "boost_clock" : "1830 Mhz"
                },
                {
                        "frame_buffer" : "6 GB GDDR6"
                },
                {
                        "memory_speed" : "336 Gbps"
                }
        ],
        "review" : [
                {
                        "name" : "dwane speed",
                        "star" : 5,
                        "review" : "rock solid graphic performance"
                },
                {
                        "name" : "michael bay",
                        "star" : 5,
                        "review" : "superb graphic rendering"
                }
        ]
}
{
        "_id" : ObjectId("5e9667164d513751c0000a4f"),
        "sku" : 1003,
        "type" : "Graphic Card",
        "model" : "GTX-1060 OC",
        "maker" : "ASUS",
        "specification" : [
                {
                        "architecture" : "turing"
                },
                {
                        "boost_clock" : "1809 Mhz"
                },
                {
                        "frame_buffer" : "6 GB GDDR6"
                },
                {
                        "memory_speed" : "336 Gbps"
                }
        ],
        "review" : [
                {
                        "name" : "igor redvlod",
                        "star" : 5,
                        "review" : "nice"
                },
                {
                        "name" : "Singh patel",
                        "star" : 4,
                        "review" : "interestingly good performance"
                }
        ]
}

Conclusion

Because it’s possible for an array to be stored as the value of a field in MongoDB, it’s important to know how to work with this type of data in your queries and commands. In this article, we focused on the process of filtering elements in an array. We showed you how to use the $filter and $elematch operators to filter array elements in MongoDB and provided examples of their use. With our instructions and examples, you’ll be prepared to use these operators in your own MongoDB queries.

Pilot the ObjectRocket Platform Free!

Try Fully-Managed CockroachDB, Elasticsearch, MongoDB, PostgreSQL (Beta) or Redis.

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.