How can you count two conditions in MongoDB?

In MongoDB, you can use the $match and $group operators to count with two conditions. Here is an example:

Assume we have a collection called users that stores user data, where each user document contains a field age representing their age and a field gender representing their gender.

To count the number of female users aged between 20 and 30, you can use the following aggregation pipeline operation:

db.users.aggregate([
  {
    $match: {
      age: { $gte: 20, $lte: 30 },
      gender: "female"
    }
  },
  {
    $group: {
      _id: null,
      count: { $sum: 1 }
    }
  }
])

In the example above, first the $match operator is used to filter out user documents that meet the criteria (age between 20 and 30 and female gender), then the $group operator is used to group the matching documents into a new document and calculate the number of documents that meet the criteria.

The results will be as follows:

{ "_id" : null, "count" : 3 }

If _id is null, it means all matching documents are grouped into the same group, and count represents the number of documents that meet the conditions.

bannerAds