How To Get The Total Number Of Returned Rows From A Query In MongoDB: Simplest Explanation

How To Get The Total Number Of Returned Rows From A Query In MongoDB: Simplest Explanation

·

1 min read

In this post, I will show you the quickest way to get the total number of results that your query returned.

When I was looking online, I could only find long-winded answers to this question, so here is my attempt at a simple and straight solution.

Here is the easiest way to get the total number of terms found from your search query:

await Model.find({your search}}.countDocuments();  (as a side note: don't miss the await as otherwise, your query will not work; that part confused me the longest time!)

So, for example, if we have a collection of "persons" and there are eight "persons" rows with a column name of firstName and a value of "John".

The following would return 8.

router.get("/", async function(req, res, next)
{
var numOfPersons = await Person.find({firstName: "John"}).countDocuments();
res.send(numOfPersons);
});

This should return us "8".

Image

Screen Shot 2022-10-05 at 3.26.42 PM.png

In Summary In summary, countDocument() after a query will return a number that is the total number of rows that matches that query.