0
0
MongoDBquery~5 mins

Querying array elements directly in MongoDB

Choose your learning style9 modes available
Introduction

Sometimes, you want to find documents where an array contains specific values. Querying array elements directly helps you do that easily.

You want to find users who have a specific hobby in their hobbies list.
You need to get orders that include a particular product ID in their items array.
You want to filter blog posts that have certain tags in their tags array.
You want to find students who scored a specific grade in any subject stored as an array.
Syntax
MongoDB
db.collection.find({ arrayField: value })

This query finds documents where arrayField contains value.

You can also use operators like $elemMatch for more complex conditions.

Examples
Finds users whose hobbies array contains the string "reading".
MongoDB
db.users.find({ hobbies: "reading" })
Finds orders where the items array contains the product ID 12345.
MongoDB
db.orders.find({ items: 12345 })
Finds posts where the tags array contains "mongodb" using $elemMatch.
MongoDB
db.posts.find({ tags: { $elemMatch: { $eq: "mongodb" } } })
Finds students with any grade greater than or equal to 90.
MongoDB
db.students.find({ grades: { $elemMatch: { $gte: 90 } } })
Sample Program

This program creates a 'students' collection with grades arrays. It then finds students who have a grade exactly equal to 90 in their grades array.

MongoDB
use school

// Insert sample documents
db.students.insertMany([
  { name: "Alice", grades: [85, 92, 78] },
  { name: "Bob", grades: [88, 90, 95] },
  { name: "Charlie", grades: [70, 75, 80] }
])

// Find students who have a grade of 90
const result = db.students.find({ grades: 90 }).toArray()

printjson(result)
OutputSuccess
Important Notes

Querying arrays directly checks if the array contains the value anywhere inside.

Time complexity depends on indexes; indexing array fields can speed up queries.

Common mistake: expecting the query to match the whole array instead of any element.

Use $elemMatch when you need to match multiple conditions on the same array element.

Summary

You can query arrays by specifying the value to find documents where the array contains it.

Simple queries check for presence of a value; $elemMatch allows complex conditions.

Indexing array fields improves query performance.