Mongoose: Counting Documents that Satisfy Conditions

Last updated on August 26, 2021 A Goodman Loading... Post a comment

Mongoose is a great open-source that is widely used when building backend with Node.js and MongoDB. It supports several built-in methods that can help us count documents that satisfy given conditions in a database collection:

  • Model.count({ /* conditions */ })
  • Model.countDocuments({/* conditions */})

Example

Let’s say we have a user model like this:

// Kindacode.com
const mongoose = require("mongoose");

const UserSchema = mongoose.Schema({
  email: {
    type: String,
    required: true,
    unique: true,
  },
  name: {
    type: String,
    required: true,
  },
  age: {
    type: Number,
    default: 0,
  },
});

const UserModel = mongoose.model("User", UserSchema);
module.exports = UserModel;

This code counts the number of users whose ages are greater than 18 but less than 65:

UserModel.count(
  {
    age: {
      $gt: 18,
      $lt: 65,
    },
  },
  function (err, count) {
    if (err) {
      throw Error("Something bad happened");
    }

    console.log(count);
  }
);

You can also use async/await instead of the callback function like this:

const countFunction = async () => {
  try {
    const count = await UserModel.count({
      age: {
        $gt: 18,
        $lt: 65,
      },
    });

    console.log(count);
  } catch (err) {
    console.log(err);
  }
};

That’s it. If you want to explore more about Node.js, take a look at the following articles:

You can also check our Node.js category page or PHP category page for the latest tutorials and examples.

Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments

You May Also Like