How to count document without query

Viewed 36

Example I have collection users like this


[
   {
       name : 'John',
       age : 21,
   },
   {
       name : 'Ethan',
       age : 23,
   },
   {
       name : 'Jack',
       age : 21,
   },
]

I want to count how many type of age (result should be 2 because age have 21 and 23) And how many of each type something like db.collection.anyFunctionForCount("help me field age please") result i expect is

{"21" : 1 , "23" : 2}
1 Answers

You need to use aggregation-framework in MongoDB default driver, or mongoose. That code should help you:

MongoPlayground example

Model.aggregate([
  {
    "$group": {
      "_id": "$age",
      "field1": {
        "$sum": 1
      }
    }
  }
])
Related