• Post author:
  • Post category:MongoDB
  • Post last modified:May 9, 2024
  • Reading time:8 mins read
You are currently viewing MongoDB Search in Array of Objects

How to search a value in an array of objects in MongoDB? There are some techniques to search for a value in an array of Objects by using find() method. In this article, we will explore how to search through arrays of objects in MongoDB using a variety of techniques from basic to complex.

Advertisements

Let’s consider a collect student with some documents that have arrays and I will use this collection to demonstrate the examples.


# Create Student Collection
db.student.insertMany([
  { 
     _id:1, 
     student_Info: [ 
        {"name":"Alice", "age": 23, "batch": 2023, 
        "address":[
             {"city":"Atlanta", "street": "XYZ"}
               ]
         } ],
        course_Info: [ {course:"Python", credit_hours: 4} ]
      
    },
    { 
        _id:2, 
        student_Info: [ 
            {"name":"Ian", "age": 21, "batch": 2021, 
             "address":[
                  {"city":"Atlanta", "street": "ABC"}
               ]
         } ],
        course_Info: [ {course:"MongoDB", credit_hours: 3} ]
      
    },
    { 
       _id:3, 
        student_Info: [ 
            {"name":"Tyler", "age": 22, "batch": 2023, 
             "address":[
                   {"city":"Georgia", "street": "LMN"}
               ]
         } ],
        course_Info: [ {course:"Java", credit_hours: 4} ]
      
    }
])

1. MongoDB Search in Array Using Basic Query

The most common way to search through arrays of objects in MongoDB is to use a basic querying method by using the find() method.

For example, we have an array of student_Info in our collection student which contains the name field in student_Info array, and we want to find the documents where the array object field name has the value Ian. The following query searches the array student_info where the name is Ian and when the condition is true, it returns all the documents.


# Usage of find query
db.student.find({ "student_Info.name": "Ian" })

It returns the below output where the array student_Info has the name equal to Ian.  

MongoDB Search in Array

2. With Regular Expression to Search in Array Objects

Alternatively, you can also use the regular expression to search within arrays of objects. For example, we have an array object course_Info in the collection student that contains the field course. We want to search for all students who have a course with a title that starts with Py.


#Usage of Regular Expression Query
db.student.find({ "course_Info.course": /^Py/ })

The output yields one document that satisfies the given regular expression to the array object.

MongoDB Search in Array objects

3. Search in Multiple Fields in an Array of Objects

In addition to the prior examples, we can also search within arrays of objects by specifying multiple fields to search for. Here, is an example.


# Usage of Multiple Fields Query
db.student.find({ "student_Info.name": "Alice",
      "student_Info.age": 23 
})

In our collection, we have a student_Info array with the fields name and age. Now, let’s query the student_Info array where it contains at least one object with a name property equal to Alice and an age property equal to 23.

The document is retrieved in the output which contains both the field with the value in the array.

4. With $elemMatch Query

Sometimes, we need to search for documents where multiple conditions must be satisfied within the same object in the array. To achieve this, we have the $elemMatch operator which is used to specify that all the specified criteria must match within the same element of the array.


# Usage of $elemMatch Query
db.student.find({ student_Info: { $elemMatch: 
   { name: "Tyler", age: 22, batch: { $gt: 2022 } } 
 } })

Here we have a query where the $elemMatch operator is called to search the documents that contain an element in the student_Info array that matches the specified criteria. The criteria include the name Tyler, an age of 22, and a batch number greater than 2022.

The output is fetched which matches the specified criteria.

MongoDB Search in Array

5. Search in Array of Nested Objects

Further, the objects nested within arrays of objects can also be searched.


# Usage of Nested Object Query
db.student.find({ "student_Info.name": "Ian", 
  "student_Info.address.city": "Atlanta" 
})

For example, we have an array student_Info which contains another array address. and wanted to search from the nested array address. For this, we have the following query that searches the nested array address with a city property equal to Atlanta.

6. With Projection Query

Finally, we have an alternate option which is a projection to filter out the array if we want to return only the matching objects in an array.

For example, let’s say we want to search from the course_Info array object containing a course field and a credit_hours field. We have the following query which searches through the “course_Info” array for any objects that contain a credit_hours field with the value 4.  It then uses projection to return only the matching objects with the specified field.


# Usage of Projection Query
db.student.find({ "course_Info.credit_hours": 4 }, 
  { "course_Info.$": 1 }
 )

The output shows the documents where the credit_hours are 4 in the course_Info array.

MongoDB Search in Array

7. Conclusion

In conclusion, searching within arrays of objects in MongoDB can be achieved using various techniques discussed above. We can use these examples as a jumping-off point for more complicated queries.