🎓 A1Learner
🔍
0 of 50 lessons completed

Counting Documents

Counting documents answers how many match, without fetching the documents themselves. countDocuments takes a filter and returns a number.

Count them all

No filter means every document in the collection is counted.

const total = await Note.countDocuments();

Count the matches

The filter counts only the finished notes.

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

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 },
  { title: 'Ship MERN', done: true, priority: 3 },
  { title: 'Read a book', done: false, priority: 2 }
]);

console.log(await Note.countDocuments());
console.log(await Note.countDocuments({ done: true }));
console.log(await Note.countDocuments({ done: false }));

await mongoose.disconnect();

Key points

  • countDocuments with no filter counts every document in the collection.
  • A filter counts only the documents that match it.
  • The result is a plain number, not a list of documents.
  • Counting is lighter than fetching, since no document data comes back.
  • The same filter used in a find can be used in a count.

In this example, three notes are saved first. The first count has no filter, so it returns 3. The second count filters on done, so it returns 1. The third count filters on unfinished notes, so it returns 2.

Note

A count of zero means no document matched, not an error.

Try it Yourself

Edit the code, then press Run.

Running is simulated

Exercise

What does countDocuments return?