Elementposition abgleichen
In diesem Schritt werden wir lernen, wie man MongoDB-Arrays abfragt, indem man spezifische Elementpositionen abgleicht. MongoDB bietet leistungsstarke Möglichkeiten, um nach Elementen an exakten Positionen innerhalb eines Arrays zu suchen.
Lassen Sie uns zunächst die MongoDB-Shell starten und sicherstellen, dass wir unsere vorherige Datenbank verwenden:
mongosh
use arraylab
Lassen Sie uns eine neue Sammlung mit Dokumenten erstellen, die Arrays haben, bei denen die Position der Elemente wichtig ist:
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"]
}
]);
Jetzt lassen Sie uns Dokumente abfragen, indem wir Elemente an bestimmten Arraypositionen abgleichen:
// 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" });
Beispielausgabe:
// 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' ]
}
]
Sie können auch positionbasierte Abfragen mit anderen Bedingungen kombinieren:
// Find courses where the first module is "HTML" and the second difficulty is "intermediate"
db.courses.find({
"modules.0": "HTML",
"difficulty.1": "intermediate"
});