0
0
MongoDBquery~5 mins

Why querying nested data matters in MongoDB

Choose your learning style9 modes available
Introduction

Nested data stores information inside other information, like a box inside a bigger box. Querying nested data helps you find details deep inside your data quickly and easily.

You want to find a friend's phone number stored inside their contact details.
You need to get all comments inside a blog post document.
You want to check the status of an order inside a customer's order history.
You want to filter products by a feature stored inside a nested list.
You want to update a specific address inside a user's multiple addresses.
Syntax
MongoDB
db.collection.find({ 'nested.field': value })
Use dot notation to reach inside nested objects or arrays.
This syntax works for querying fields inside embedded documents.
Examples
Find users who live in the city named New York inside their address.
MongoDB
db.users.find({ 'address.city': 'New York' })
Find posts where any comment was written by Alice.
MongoDB
db.posts.find({ 'comments.author': 'Alice' })
Find orders that include an item with the product named Book.
MongoDB
db.orders.find({ 'items.product': 'Book' })
Sample Program

This example adds three users with nested address info. Then it finds users who live in New York by looking inside the nested address field.

MongoDB
db.users.insertMany([
  { name: 'John', address: { city: 'New York', zip: '10001' } },
  { name: 'Jane', address: { city: 'Boston', zip: '02101' } },
  { name: 'Mike', address: { city: 'New York', zip: '10002' } }
])

// Query users living in New York
 db.users.find({ 'address.city': 'New York' })
OutputSuccess
Important Notes

Remember to use quotes around nested field names with dot notation.

Querying nested data is powerful for complex documents but can be slower if indexes are missing.

Summary

Nested data stores information inside other information.

Use dot notation to query inside nested fields.

Querying nested data helps find detailed info quickly.