Use mongoose to find in an Array of Objects

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

Introduction

In this tutorial we will discuss how to use mongoose to find in an array of objects.

Searching in an Array of Objects

In the programming world, arrays are one of the most widely used data structures. Arrays are used on both client-side and server-side. They are heavily used in NoSQL databases also. In MongoDB, arrays are one of the supported data types. We can even store an array of objects as a value of the key. Just observe the following document.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
{
       "_id" : ObjectId("5e19d76fa45abb5d4d50c1d3"),
       "name" : "Leonel Messi",
       "age" : 32,
       "country" : "Argentina",
       "awards" : [
               {
                       "award" : "Ballon d'Or",
                       "numberOfTimes" : 6
               },
               {
                       "award" : "Golden Boot",
                       "numberOfTimes" : 6
               },
               {
                       "award" : "FIFA World Player of the Year",
                       "numberOfTimes" : 1
               }
       ]
}

The above document contains details about the Argentine footballer Leonel Messi. Observe the “awards” field.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
"awards" : [
        {
            "award" : "Ballon d'Or",
            "numberOfTimes" : 6

        },
        {
            "award" : "Golden Boot",
            "numberOfTimes" : 6

        },
        {
            "award" : "FIFA World Player of the Year",
            "numberOfTimes" : 1

        }




    ]

Its value is an array of objects and each object contains two fields – “award” and “numberOfTimes”. In this article, we will discuss how to use the find() method with an array of objects in mongoose.

We will be using a football collection. It has two documents with similar key-value pairs.

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
{
       "_id" : ObjectId("5e19d76fa45abb5d4d50c1d3"),
       "name" : "Leonel Messi",
       "age" : 32,
       "country" : "Argentina",
       "awards" : [
               {
                       "award" : "Ballon d'Or",
                       "numberOfTimes" : 6
               },
               {
                       "award" : "Golden Boot",
                       "numberOfTimes" : 6
               },
               {
                       "award" : "FIFA World Player of the Year",
                       "numberOfTimes" : 1
               }
       ]
}
{
       "_id" : ObjectId("5e19d791a45abb5d4d50c1d4"),
       "name" : "Cristiano Ronaldo",
       "age" : 34,
       "country" : "Portugal",
       "awards" : [
               {
                       "award" : "Ballon d'Or",
                       "numberOfTimes" : 5
               },
               {
                       "award" : "Golden Boot",
                       "numberOfTimes" : 4
               },
               {
                       "award" : "FIFA World Player of the Year",
                       "numberOfTimes" : 1
               }
       ]
}

We will use the postman tool for endpoint testing. The following route handler will be invoked when the endpoint ‘/find’ will be executed.

NOTE We are using the express framework in NodeJS to create our API endpoints.

1
router.route("/find").get(function(req, res) {});

Now, if we want to get all the documents where the value of the country field is “Portugal”, we can simply use the following approach.

1
find({ country: "Portugal" });

But, what if we want all the documents where:

  1. The awards array contains an object that has “Golden Boot” as the value of the award field.
  2. In the same object, the value of the numberOfTimes field is 6.

Simply said, We want to search for the soccer player who has won 6 Golden Boot awards. So how can we do this? In the query, we need to provide a condition accordingly. But here we need to access something inside an object, and that object is inside an array, and that array, in turn, is the value of the awards field. Observe the following.

1
"awards.award";

This is how we can access a key of an object inside an array. So let’s see how can we achieve our requirements here.

1
{"awards.award":  "Golden Boot", "awards.numberOfTimes": 6}

Let’s add this to the find() method in the route and execute it using the postman tool.

1
2
3
4
5
6
7
8
9
10
11
12
router.route("/find").get(function(req, res) {
  football.find(
    { "awards.award": "Golden Boot", "awards.numberOfTimes": 6 },
    function(err, result) {
      if (err) {
        res.send(err);
      } else {
        res.json(result);
      }
    }
  );
});

Image from Gyazo

As you can see this find query we created returns exactly the playing we were looking for. It works perfectly!

Conclusion

So remember, when accessing an array of objects in mongoose, we have to use a dot(.) followed by the field name of the object. Searching inside of an array is very common and it will come in handy so it is great to have it mastered. Thank you for joining us for another Object Rocket knowledge-base tutorial.

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.