How to group records by a field in mongoose?

Member

by gilbert , in category: MySQL , a month ago

How to group records by a field in mongoose?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

Member

by rollin , a month ago

@gilbert 

To group records by a field in Mongoose, you can use the aggregate function provided by Mongoose. Here is an example of how you can group records by a specific field:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
// Assume you have a Mongoose model called 'User' with a field 'age'

User.aggregate([
  { 
    $group: {
      _id: '$age',
      count: { $sum: 1 }
    }
  }
], function(err, result) {
  if (err) {
    console.error(err);
  } else {
    console.log(result);
  }
});


In this example, we are using the aggregate function to group records from the 'User' collection by the 'age' field. The $group stage is used to group the documents by the 'age' field and then calculate the count of each group using the $sum accumulator. The result will be an array of objects where each object contains the _id (the age) and the count of records with that age.


You can customize the grouping logic based on your specific requirements by adding more stages to the aggregate pipeline.