Daten mit Mongoose abfragen und filtern
Gehen Sie über einfaches CRUD hinaus und lernen Sie, mit Mongoose leistungsfähige Abfragen mithilfe von Filtern, Operatoren, Sortierung, Paginierung und Projektionen zu erstellen.
Daten mit Mongoose abfragen und filtern ist eine kostenlose Node.js Backend Development Bootcamp-Lektion auf CoddyKit. Dies ist Lektion 4 von 4. Du kannst die komplette Lektion unten kostenlos lesen – dann übst du sie direkt im Browser mit einem integrierten Code-Editor und einem KI-Tutor rund um die Uhr. Sie ist Teil des Node.js Backend Development Bootcamp-Lernpfads, und dein Fortschritt wird über Web und CoddyKit-App synchronisiert. Der Node.js Backend Development Bootcamp-Kurs umfasst insgesamt 4 Lektionen.
Teile dieser Lektion wurden noch nicht übersetzt und werden auf Englisch angezeigt.
Beyond Find-All
Fetching every document with Model.find() works for tiny collections, but real apps need to filter, sort, limit, and shape their results.
Mongoose gives you a fluent query API that mirrors MongoDB's query language.
const users = await User.find({ active: true });Filtering by Field
Pass an object to find() to match documents by exact field values. Multiple keys are combined with logical AND.
const admins = await User.find({ role: 'admin', active: true });Comparison Operators
MongoDB operators start with $. The most common comparisons are:
$gt/$gtegreater than (or equal)$lt/$lteless than (or equal)$nenot equal
const adults = await User.find({ age: { $gte: 18 } });Matching Multiple Values
Use $in to match any value from a list, and $nin to exclude a list. This is cleaner than chaining many OR conditions.
const team = await User.find({ role: { $in: ['admin', 'editor'] } });Logical OR
The $or operator takes an array of conditions; a document matches if any one is true.
const results = await User.find({
$or: [{ city: 'Berlin' }, { city: 'Paris' }]
});Sorting Results
Chain .sort() to order results. Use 1 for ascending and -1 for descending. You can sort by multiple fields.
const recent = await User.find().sort({ createdAt: -1, name: 1 });Limiting and Skipping
Pagination relies on .limit() (max documents) and .skip() (how many to bypass). For page 2 with 10 per page, skip 10 and limit 10.
const page = 2, perPage = 10;
const items = await User.find()
.skip((page - 1) * perPage)
.limit(perPage);Selecting Specific Fields
Use .select() (projection) to return only the fields you need. Prefix a field with - to exclude it. This reduces payload size and hides sensitive data.
const safe = await User.find().select('name email -_id');
const noPass = await User.find().select('-password');Finding a Single Document
findOne() returns the first match or null. findById() is a shortcut for matching by _id.
const user = await User.findOne({ email: 'a@b.com' });
const byId = await User.findById('652f1c...');Counting Documents
To know how many documents match a filter without fetching them all, use countDocuments(). This is essential for showing total pages in pagination.
const total = await User.countDocuments({ active: true });
console.log('Active users:', total);Text & Regex Search
For partial matches, use a regular expression. The $regex operator with the i option makes a case-insensitive search.
const matches = await User.find({
name: { $regex: 'an', $options: 'i' }
});Quick Check
Test your Mongoose querying skills.
Recap
You can now build rich Mongoose queries:
- Filter by field and combine with operators like
$gte,$in,$or - Order results with
.sort() - Paginate with
.skip()and.limit() - Shape output with
.select() - Count matches with
countDocuments()
These tools turn a basic data layer into a flexible, production-ready API.
Häufig gestellte Fragen
Ist die Lektion „Daten mit Mongoose abfragen und filtern“ kostenlos?
Ja — der vollständige Text von „Daten mit Mongoose abfragen und filtern“ ist hier im Web kostenlos zu lesen. Um sie interaktiv zu üben (integrierter Code-Editor und 24/7 KI-Tutor) und den Rest des Node.js Backend Development Bootcamp-Kurses freizuschalten, upgrade auf CoddyKit PRO. Der Node.js Backend Development Bootcamp-Kurs umfasst insgesamt 4 Lektionen.
Was lerne ich in „Daten mit Mongoose abfragen und filtern“?
Gehen Sie über einfaches CRUD hinaus und lernen Sie, mit Mongoose leistungsfähige Abfragen mithilfe von Filtern, Operatoren, Sortierung, Paginierung und Projektionen zu erstellen. Du übst Node.js Backend Development Bootcamp mit praktischem Code, den du direkt im Browser ausführst, und ein 24/7 KI-Tutor beantwortet deine Fragen während du die Lektion bearbeitest.
Brauche ich Erfahrung, um Node.js Backend Development Bootcamp zu starten?
Keine Vorkenntnisse erforderlich. Node.js Backend Development Bootcamp auf CoddyKit ist für Anfänger bis fortgeschrittene Lernende strukturiert, sodass du hier starten oder von Anfang an beginnen und in deinem eigenen Tempo voranschreiten kannst. Dies ist Lektion 4 von 4.
Wie lange dauert die Lektion „Daten mit Mongoose abfragen und filtern“?
Die meisten CoddyKit-Lektionen dauern etwa 5–10 Minuten. Jede ist kompakt und interaktiv, sodass du stetig Fortschritte machst und genau dort weitermachst, wo du aufgehört hast – im Web und in der App.
Kann ich in dieser Node.js Backend Development Bootcamp-Lektion Code schreiben und ausführen?
Ja. Jede Node.js Backend Development Bootcamp-Lektion enthält einen integrierten Code-Editor, sodass du echten Code direkt in deinem Browser schreibst und ausführst und sofort KI-Feedback erhältst — ohne lokale Einrichtung erforderlich.
Alle Lektionen in diesem Kurs
- Node.js mit MongoDB verbinden
- Mongoose ODM für Datenmodellierung
- CRUD-Operationen mit Mongoose
- Daten mit Mongoose abfragen und filtern