How to group records by a field in mongoose?

Member

by gilbert , in category: MySQL , 5 months ago

How to group records by a field in mongoose?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

Member

by rollin , 5 months 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.

Related Threads:

How to group records based on array elements using mongodb?
How to group time column into 5 second intervals and count rows using presto?
How to get latest 3 months records in presto sql?
How to store records ascending based on timestamp?
How to group datetime into intervals of 3 hours in mysql?
How to use mongoose and koa.js?