0
0
MongoDBquery~5 mins

Querying nested fields at any depth in MongoDB

Choose your learning style9 modes available
Introduction

Sometimes data is stored inside other data. We need to find information deep inside these layers.

You want to find a friend's phone number inside their address book stored in a database.
You need to get the price of a product inside a list of product details.
You want to check if a comment inside a post has a certain word.
You want to find a user whose profile has a nested setting turned on.
Syntax
MongoDB
{ 'outer.inner.deep': value }

Use dots (.) to go inside nested fields.

Replace 'outer.inner.deep' with your actual nested field names.

Examples
Finds documents where the city inside the address is 'New York'.
MongoDB
{ 'address.city': 'New York' }
Finds products with a price of 100 inside their details.
MongoDB
{ 'product.details.price': 100 }
Finds documents where any comment's text is 'great'.
MongoDB
{ 'comments.text': 'great' }
Sample Program

This finds users whose email inside profile > contact is 'alice@example.com'.

MongoDB
db.users.find({ 'profile.contact.email': 'alice@example.com' })
OutputSuccess
Important Notes

If the nested field does not exist, the query will not match that document.

You can use this dot notation with other query operators like $gt, $lt, $in.

Summary

Use dot notation to reach inside nested fields.

This helps find data stored deep inside documents.

It works with any depth of nesting.