Sometimes, you want to find documents where an array contains specific values. Querying array elements directly helps you do that easily.
Querying array elements directly in 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.
db.users.find({ hobbies: "reading" })db.orders.find({ items: 12345 })db.posts.find({ tags: { $elemMatch: { $eq: "mongodb" } } })db.students.find({ grades: { $elemMatch: { $gte: 90 } } })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.
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)
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.
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.