From the docs. It's db.collection.count
. Don't use find
.
Returns the count of documents that would match a find() query for the
collection or view. The db.collection.count() method does not perform
the find() operation but instead counts and returns the number of
results that match a query.
Example Usage:
const MongoClient = require('mongodb').MongoClient;
// Connection url
const url = 'mongodb://localhost:27017';
// Database Name
const dbName = 'users';
// Connect using MongoClient
MongoClient.connect(url, function(err, client) {
const db = client.db(dbName);
const email = 'foo@bar.com';
const query = { email: email };
const options = {};
db.collection.count(query, options, (err, result) => {
// handle error
if (err) {
console.log(err);
}
// do something with result
console.log(result);
});
});
Here is a basic example of how count
might work. I assume you are using the mongodb
npm and not mongoose
or other mongo wrappers like it. The way I would use this in a project is by making the connection to your mongodb its own module so that it can be reused with other queries. That way you don't have to wrap every query with a connection.