Home > Enterprise >  mongoose countDocuments multiple keys
mongoose countDocuments multiple keys

Time:11-06

I have setup a Node get request to return the count of the keys in my database. However atm it returns the count of one key. I'd like to know how to add more keys to count. So instead of only counting Medium, I'd also like to count Small and Large.

    registerRoute.route("/countDocuments").get(function (req, res) {
   Sweatersizes.countDocuments({ sweatersize: "Medium" }, function (err, result) {
    if (err) {
      res.send(err);
    } else {
      res.json(result);
    }
  });
});

Thanks!

CodePudding user response:

Query

  • you can use group, and sum them seperatly

Test code here

aggregate(
[{"$group": 
   {"_id": "$sweatersize",
    "count": {"$sum": 1},
    "sweatersize": {"$first": "$sweatersize"}}},
 {"$unset": ["_id"]}])

CodePudding user response:

You can do it with Aggregation framework and group pipeline:

registerRoute.route("/countDocuments").get(function (req, res) {
   Sweatersizes.aggregate([
     {
       "$group": {
         "_id": "$sweatersize",
         "total_count": {
           "$count": {}
         }
       }
     }
    ], function (err, result) {
      if (err) {
        res.send(err);
      } else {
        res.json(result);
      }
   });
});

Working example

  • Related