MongoDB Array Queries
MongoDB documents can hold lists of values called arrays. A student document may carry a list of subjects, and a product document may carry a list of tags. Special query tools let you search inside these lists without extra effort.
Sample Data
The examples below use a collection named courses. Insert these documents to follow along:
db.courses.insertMany([
{ title: "Web Basics", tags: ["html", "css"], scores: [70, 85, 90] },
{ title: "Python Start", tags: ["python", "coding"], scores: [60, 75] },
{ title: "Full Stack", tags: ["html", "css", "node"], scores: [88, 92, 95, 80] }
])Picture of an Array Field
{
title: "Full Stack",
tags: [ "html" , "css" , "node" ]
[0] [1] [2] <-- position numbers start at 0
}Each value in the list has a position number. The first value sits at position 0.
Find a Single Value in an Array
A normal equality filter checks whether the array contains the value:
db.courses.find({ tags: "css" })This query returns Web Basics and Full Stack, because both lists include css. MongoDB looks through every element for you.
Find by Position
Use dot notation with a position number to test one exact spot:
db.courses.find({ "tags.0": "html" })This query returns courses whose first tag is html.
Match an Exact Array
Give the full array as the filter to match the same values in the same order:
db.courses.find({ tags: ["html", "css"] })Only Web Basics matches. Full Stack has an extra value, and a reversed list such as ["css", "html"] would fail too.
Array Operators
$all: Contains Every Listed Value
The $all operator ignores order and extra values:
db.courses.find({ tags: { $all: ["css", "html"] } })Web Basics and Full Stack both match because each holds html and css somewhere in the list.
$in: Contains At Least One Listed Value
db.courses.find({ tags: { $in: ["python", "node"] } })The result includes Python Start and Full Stack. A document needs only one of the listed values to qualify.
$size: Has an Exact Length
db.courses.find({ tags: { $size: 2 } })The result holds courses with exactly two tags. The $size operator accepts only exact numbers, so it cannot test for "more than two". Store a count field in the document when you need range checks on length.
$elemMatch: One Element Meets Several Conditions
Conditions placed directly on an array can match different elements. Take this query:
db.courses.find({ scores: { $gt: 90, $lt: 85 } })No single number can sit above 90 and below 85 at once. The query still returns Full Stack, because the score 92 satisfies the first condition and the score 80 satisfies the second condition. MongoDB lets each condition pick its own element. The $elemMatch operator forces both conditions onto the same element:
db.courses.find({ scores: { $elemMatch: { $gt: 90, $lt: 85 } } })This version returns nothing, which is the correct answer for an impossible range. A realistic range such as { $gte: 85, $lte: 90 } inside $elemMatch finds courses with at least one score between 85 and 90.
Arrays of Documents
The operator shines when an array holds small documents:
{ name: "Kavya", exams: [ { subject: "Math", marks: 90 }, { subject: "Art", marks: 55 } ] }
db.students.find({ exams: { $elemMatch: { subject: "Math", marks: { $gte: 80 } } } })The query finds students who scored 80 or more in Math. Without $elemMatch, a student with 90 in Art and 40 in Math could match by mistake.
Decision Diagram
What do you need?
|
+-- One value inside the list ........ { field: value }
+-- All listed values ................ $all
+-- Any listed value ................. $in
+-- Exact list length ................ $size
+-- Several rules on one element ..... $elemMatch
+-- Exact list, exact order .......... { field: [ ... ] }Project Part of an Array
The $slice projection returns only some elements from an array:
db.courses.find({}, { title: 1, scores: { $slice: 2 } })Each result shows the title and the first two scores. A negative number such as -2 returns the last two scores.
Speed Up Array Searches
An index on an array field creates one index entry for every element. Developers call this a multikey index:
db.courses.createIndex({ tags: 1 })Queries on tags run faster after this index exists.
Summary
MongoDB treats array search as a natural part of querying. A plain filter checks whether the list contains a value. The $all, $in, and $size operators handle common list questions. The $elemMatch operator keeps several conditions tied to one element, which matters most for arrays of documents. A multikey index keeps these searches quick as the collection grows.
