0
0
MongoDBquery~5 mins

Array of embedded documents queries in MongoDB

Choose your learning style9 modes available
Introduction

We use array of embedded documents queries to find or work with data inside lists of small documents stored inside a bigger document. This helps us get specific info from complex data easily.

You have a list of orders inside a customer record and want to find customers with a specific order.
You want to find products where one of the reviews has a certain rating.
You need to update or find a specific item inside a list of addresses stored in a user profile.
You want to count how many documents have an embedded document with a certain property.
Syntax
MongoDB
db.collection.find({ 'arrayField.key': value })

This syntax searches for documents where the array arrayField contains at least one embedded document with key equal to value.

You can use dot notation to access fields inside embedded documents in arrays.

Examples
Find customers who have at least one order with product named 'Book'.
MongoDB
db.customers.find({ 'orders.product': 'Book' })
Find products with at least one review having rating 4 or higher.
MongoDB
db.products.find({ 'reviews.rating': { $gte: 4 } })
Find users who have an address in the city 'New York'.
MongoDB
db.users.find({ 'addresses.city': 'New York' })
Find orders where any item has quantity greater than 10.
MongoDB
db.orders.find({ 'items.quantity': { $gt: 10 } })
Sample Program

This program adds three customers with their orders. Then it finds customers who have ordered the product 'Book'.

MongoDB
db.customers.insertMany([
  {
    name: 'Alice',
    orders: [
      { product: 'Book', quantity: 2 },
      { product: 'Pen', quantity: 5 }
    ]
  },
  {
    name: 'Bob',
    orders: [
      { product: 'Notebook', quantity: 1 }
    ]
  },
  {
    name: 'Carol',
    orders: [
      { product: 'Book', quantity: 1 },
      { product: 'Pencil', quantity: 3 }
    ]
  }
])

// Find customers who ordered 'Book'
db.customers.find({ 'orders.product': 'Book' }).pretty()
OutputSuccess
Important Notes

Querying arrays of embedded documents uses dot notation to reach inside the array elements.

These queries check if any embedded document in the array matches the condition.

Use $elemMatch operator if you want to match multiple conditions on the same embedded document.

Summary

Use dot notation to query inside arrays of embedded documents.

Queries match if any embedded document in the array meets the condition.

For multiple conditions on one embedded document, use $elemMatch.