Match Element Position
In this step, we'll learn how to query MongoDB arrays by matching specific element positions. MongoDB provides powerful ways to search for elements at exact locations within an array.
First, let's start the MongoDB shell and ensure we're using our previous database:
mongosh
use arraylab
Let's create a new collection with documents that have arrays where the position of elements matters:
db.courses.insertMany([
{
name: "Web Development Bootcamp",
modules: ["HTML", "CSS", "JavaScript", "React", "Node.js"],
difficulty: ["beginner", "intermediate", "advanced"]
},
{
name: "Data Science Course",
modules: [
"Python",
"Statistics",
"Machine Learning",
"Deep Learning",
"AI"
],
difficulty: ["intermediate", "advanced", "expert"]
},
{
name: "Cybersecurity Program",
modules: [
"Network Security",
"Ethical Hacking",
"Cryptography",
"Penetration Testing",
"Incident Response"
],
difficulty: ["intermediate", "advanced", "expert"]
}
]);
Now, let's query documents by matching elements at specific array positions:
// Find courses where the first module is "HTML"
db.courses.find({ "modules.0": "HTML" });
// Find courses where the third module is "JavaScript"
db.courses.find({ "modules.2": "JavaScript" });
// Find courses where the second difficulty level is "advanced"
db.courses.find({ "difficulty.1": "advanced" });
Example output:
// Courses with HTML as the first module
[
{
_id: ObjectId("..."),
name: 'Web Development Bootcamp',
modules: [ 'HTML', 'CSS', 'JavaScript', 'React', 'Node.js' ],
difficulty: [ 'beginner', 'intermediate', 'advanced' ]
}
]
// Courses with JavaScript as the third module
[
{
_id: ObjectId("..."),
name: 'Web Development Bootcamp',
modules: [ 'HTML', 'CSS', 'JavaScript', 'React', 'Node.js' ],
difficulty: [ 'beginner', 'intermediate', 'advanced' ]
}
]
// Courses with "advanced" as the second difficulty level
[
{
_id: ObjectId("..."),
name: 'Data Science Course',
modules: [ 'Python', 'Statistics', 'Machine Learning', 'Deep Learning', 'AI' ],
difficulty: [ 'intermediate', 'advanced', 'expert' ]
},
{
_id: ObjectId("..."),
name: 'Cybersecurity Program',
modules: [ 'Network Security', 'Ethical Hacking', 'Cryptography', 'Penetration Testing', 'Incident Response' ],
difficulty: [ 'intermediate', 'advanced', 'expert' ]
}
]
You can also combine position-based queries with other conditions:
// Find courses where the first module is "HTML" and the second difficulty is "intermediate"
db.courses.find({
"modules.0": "HTML",
"difficulty.1": "intermediate"
});