countDocuments

noun

say it: “KOWNT DOK-yuh-ments” /kaʊnt ˈdɑkjəmənts/

A MongoDB method that returns how many documents match a filter, without fetching them.

What does countDocuments do?

countDocuments counts the documents in a collection that match a filter, without sending any of them back. It's how a paged list can say "page 2 of 3".

const filter = { organic: true };
const total = await vendors.countDocuments(filter);
const pages = Math.ceil(total / 10);
console.log(`${total} organic vendors, ${pages} pages`);

In a sentence

  • “countDocuments with an empty filter counts every document in the collection.”
  • “The vendor list calls countDocuments to show "23 vendors" above the first page.”

Level: Apprentice · More MongoDB terms at this level

Updated