0Pricing
Node.js Backend Development Bootcamp · Lezione

Query e filtri dei dati con Mongoose

Andate oltre il CRUD di base e imparate a creare query avanzate in Mongoose usando filtri, operatori, ordinamento, paginazione e proiezioni.

Query e filtri dei dati con Mongoose è una lezione Node.js Backend Development Bootcamp gratuita su CoddyKit. Questa è la lezione 4 di 4. Puoi leggere la lezione completa qui gratuitamente — poi esercitati direttamente nel browser con un editor di codice integrato e un tutor IA disponibile 24/7. Fa parte del percorso di apprendimento Node.js Backend Development Bootcamp, e i tuoi progressi si sincronizzano tra il web e l'app CoddyKit. Il corso Node.js Backend Development Bootcamp include 4 lezioni in totale.

Parti di questa lezione non sono ancora state tradotte e vengono mostrate in inglese.

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 / $gte greater than (or equal)
  • $lt / $lte less than (or equal)
  • $ne not 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.

Domande Frequenti

La lezione «Query e filtri dei dati con Mongoose» è gratuita?

Sì — il testo completo di «Query e filtri dei dati con Mongoose» è gratuito qui sul web. Per esercitarvi in modo interattivo (un editor di codice integrato e un tutor IA 24/7) e sbloccare il resto del corso Node.js Backend Development Bootcamp, passa a CoddyKit PRO. Il corso Node.js Backend Development Bootcamp include 4 lezioni in totale.

Cosa imparerò in «Query e filtri dei dati con Mongoose»?

Andate oltre il CRUD di base e imparate a creare query avanzate in Mongoose usando filtri, operatori, ordinamento, paginazione e proiezioni. Eserciti Node.js Backend Development Bootcamp con codice pratico che esegui direttamente nel browser, e un tutor IA 24/7 risponde alle tue domande mentre lavori sulla lezione.

Ho bisogno di esperienza per iniziare Node.js Backend Development Bootcamp?

Non è richiesta alcuna esperienza precedente. Node.js Backend Development Bootcamp su CoddyKit è strutturato per principianti e studenti avanzati, quindi puoi iniziare da qui o dall'inizio e procedere al tuo ritmo. Questa è la lezione 4 di 4.

Quanto tempo richiede la lezione «Query e filtri dei dati con Mongoose»?

La maggior parte delle lezioni CoddyKit richiede circa 5–10 minuti. Ogni lezione è breve e interattiva, quindi fai progressi costanti e riprendi esattamente da dove hai lasciato su web e app.

Posso scrivere ed eseguire codice in questa lezione Node.js Backend Development Bootcamp?

Sì. Ogni lezione Node.js Backend Development Bootcamp include un editor di codice integrato, quindi scrivi ed esegui codice reale direttamente nel tuo browser e ricevi feedback istantaneo dall'IA — nessuna configurazione locale necessaria.

Tutte le lezioni di questo corso

  1. Collegare Node.js a MongoDB
  2. ODM Mongoose per la modellazione dei dati
  3. Operazioni CRUD con Mongoose
  4. Query e filtri dei dati con Mongoose
← Torna a Node.js Backend Development Bootcamp