Query Array Content
In this step, you'll learn how to query and filter documents based on array contents in MongoDB. We'll continue working with the arraylab
database and students
collection.
First, ensure you're in the MongoDB shell:
mongosh
Switch to the arraylab
database:
use arraylab
To find documents where an array contains a specific element, use direct matching:
db.students.find({ courses: "Data Science" })
Example output:
[
{
_id: ObjectId("..."),
name: 'Alice Johnson',
age: 22,
courses: [ 'Advanced Mathematics', 'Computer Science', 'Data Science' ]
}
]
To query documents with an array that contains multiple specific elements, use the $all
operator:
db.students.find({
courses: { $all: ["Advanced Mathematics", "Computer Science"] }
})
To find documents where an array element matches a condition, use the $elemMatch
operator:
db.students.find({
grades: { $elemMatch: { $gt: 100 } }
})
This query finds documents where at least one grade is greater than 100.
To count the number of elements in an array, use the $size
operator:
db.students.find({
activities: { $size: 2 }
})
This query finds documents with exactly 2 activities.
Let's add one more document to demonstrate more complex queries:
db.students.insertOne({
name: "Charlie Brown",
courses: ["Art", "Music", "Literature"],
grades: [88, 92, 85],
activities: ["Painting Club"]
})
Now, let's do a more complex query combining multiple conditions:
db.students.find({
$and: [
{ courses: { $in: ["Art", "Music"] } },
{ grades: { $elemMatch: { $gte: 90 } } }
]
})
This query finds students who have either "Art" or "Music" in their courses AND have at least one grade of 90 or higher.