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.
Array of embedded documents queries in 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.
db.customers.find({ 'orders.product': 'Book' })db.products.find({ 'reviews.rating': { $gte: 4 } })db.users.find({ 'addresses.city': 'New York' })db.orders.find({ 'items.quantity': { $gt: 10 } })This program adds three customers with their orders. Then it finds customers who have ordered the product 'Book'.
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()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.
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.