• Post author:
  • Post category:MongoDB
  • Post last modified:May 9, 2024
  • Reading time:7 mins read
You are currently viewing Query Nested Objects in MongoDB

How to query nested objects in MongoDB? MongoDB has the ability to store nested objects in documents, deeply nested documents, and more complex data structures. In this article, we will figure out how to query nested objects in MongoDB using different examples. Here, we will use the collection student which contains the deeply nested object. The nested documents of the collection student may look like this.

Advertisements

#Create Collection
db.student.insertMany([
  { 
    _id:1, 
    student_detail: [ 
      {"name":"Andy", "age": 24, "email": "[email protected]", 
          "address":[
            {"city":"New York", "street": "S1"}
          ]
      } ]      
  },
  { 
     _id:2, 
     student_detail: [ 
       {"name":"Tyler", "age": 22, "email": "[email protected]", 
          "address":[
             {"city":"New York", "street": "S2"}
           ]
      } ]
  },
  { 
     _id:3, 
     student_detail: [ 
       {"name":"Kalus", "age": 24,"email": "[email protected]", 
         "address":[
             {"city":"Georgia", "street": "S2"}
         ]
     } ]
 }
])

1. Query for a Specific Nested Object in MongoDB

To query a field in the nested object in MongoDB use the find() method by referring to the nested field using the dot notation.

In this example, we query for a particular field from the nested object that meets the specified criteria, the dot notation is the most common approach to accomplish this.

The following query searches for documents in the student collection that has a sub-document called student_detail with a field called name whose value is Andy. The dot notation is specified between the field student_detail and the nested field name.


# Usage of dot notation to query nested object
db.student.find({"student_detail.name": "Andy"}) 

This yields the below output that matched the query for a nested object.

MongoDB query nested objects

2. Query for Multiple Nested Objects

We can also query for multiple nested objects in MongoDB by specifying multiple objects to be matched within the document.

For example, we have given a query below which searches for the documents in the student collection where the name field within the student_detail sub-document matches the string Tyler and the email field within the same student_detail sub-document matches the string [email protected].


# Query multiple nested objects
db.student.find({"student_detail.name": "Tyler",
                 "student_detail.email": "[email protected]"
      })

The output is returned with the document that matched the criteria of multiple nested objects.

3. Query Nested Object of Multiple Levels

Moreover, we can also query by deeply nested array objects. In our example collection, every document in the collection student includes a deeply nested object with fields for student_detail and address. Furthermore, we can query all documents where the city field inside the address field inside the student_detail field contains a specific value.


# Query nested array objects with multiple levels deep
db.student.find({"student_detail.address.city": "New York"})

This yields the below output.

MongoDB query nested objects

4. Query Nested Field with a Regular Expression

You can also use the regular expression in MongoDB to search for a field in nested object. We should use the $regex operator with a regular expression pattern to match the field value. For example, we have a query below which returns all documents in the collection that match the specified query criteria.

The criteria are specified with the $regex operator which matches the regular expression pattern /22@/ against the value of the email field within the student_detail sub-document.


# Query nested Object with $regex operator
db.student.find({"student_detail.email": /22@/})

The output displayed a document that matches the given regular expression of the nested object email.

5. Query for a specific nested object existence

Alternatively, we can query for nested objects with the $exists operator of MongoDB. The $exists operator in MongoDB is used to check whether a field exists in a document or not.

For example, we have the following query that searches for documents in the student collection where the address sub-document contains a field called street.


# Usage of $exists operator
db.student.find({"student_detail.address.street": {"$exists": true}})

The resultant output displayed all the documents where nested objects existed.

MongoDB query nested objects

6. Conclusion

In conclusion, to query nested objects in MongoDB, these are just a few examples. The best technique to use depends on the structure of the data and the specific requirements of the application.

More details about this topic can be found here.