🎓 A1Learner
🔍
0 of 50 lessons completed

Finding with Filters

A filter narrows a find to the documents that match it. The filter is an object, and each key names a field to match.

Only done notes

The filter keeps only notes where done is true.

const done = await Note.find({ done: true });

More than one field

Both parts must match, so only one note is returned.

const open = await Note.find({ done: false, priority: 1 });

A range of values

$gt means greater than, so this keeps priorities above 1.

const top = await Note.find({ priority: { $gt: 1 } });

Example

import mongoose from 'mongoose';

const noteSchema = new mongoose.Schema({
  title: String,
  done: Boolean,
  priority: Number
});

const Note = mongoose.model('Note', noteSchema);

await mongoose.connect('mongodb://localhost:27017/notes');

await Note.create({ title: 'Buy milk', done: false, priority: 1 });
await Note.create({ title: 'Ship MERN', done: true, priority: 3 });
await Note.create({ title: 'Read a book', done: false, priority: 2 });

const doneNotes = await Note.find({ done: true });
console.log(doneNotes.map(n => n.title));

const openNotes = await Note.find({ done: false });
console.log(openNotes.map(n => n.title));

await mongoose.disconnect();

Key points

  • find with no filter returns every document in the collection.
  • A filter like { done: true } returns only documents where done is true.
  • A filter can name more than one field, and all parts must match.
  • Comparison helpers such as $gt match a range of values.
  • A filter that matches nothing returns an empty list, not an error.

In this example, three notes are saved first. The first find uses the filter { done: true }, so it returns only the finished note. The second find uses { done: false }, so it returns the two unfinished notes in title order.

Note

Filter keys use the field names from the schema.

Try it Yourself

Edit the code, then press Run.

Running is simulated

Exercise

Which find returns only the notes that are done?