Skip to content
Related Articles
Open in App
Not now

Related Articles

Mongoose Aggregate.prototype.sortByCount() API

Improve Article
Save Article
  • Last Updated : 06 Dec, 2022
Improve Article
Save Article

The Aggregate sortByCount() method of the Mongoose API is used for performing aggregation tasks. It allows us to sort and counts the number of objects present in the collection for a particular value of a field.

Syntax:

aggregate().sortByCount(expression)

Parameters: This method accepts a single parameter as mentioned above and described below:

  • expression: It is used to specify the name of the column or field which you want to sort and count.

Return Value: It returns an object array, each object will have _id and count keys where _id will be the distinct value of a given field and count will be its number of occurrences.

Setting up Node.js Mongoose Module:

Step 1: Create a Node.js application using the following command:

npm init

Step 2: After creating the NodeJS application, Install the required module using the following command:

npm install mongoose

Project Structure: The project structure will look like this: 

 

Database Structure: The database structure will look like this, the following documents are present in the collection.

 

Example 1: In this example, We have established a database connection using mongoose and defined model over phoneSchema, having three columns or fields “name”, “companyName” and “manufacturingYear”. At the end, we are calling sortByCount() method and passing field name as string value for which we want sortByCount functionality.

Filename: app.js

Javascript




// Require mongoose module
const mongoose = require("mongoose");
  
// Set Up the Database connection
    useNewUrlParser: true,
    useUnifiedTopology: true,
});
  
const phoneSchema = new mongoose.Schema({
    name: String,
    companyName: String,
    manufacturingYear: Number,
});
  
const Phone = mongoose.model('Phone', phoneSchema);
  
Phone.aggregate()
    .sortByCount('manufacturingYear')
    .then(result => {
        console.log(result);
    }).catch(err => {
        console.log(err);
    })


Step to run the program: To run the application execute the below command from the root directory of the project:

node app.js

Output:

[
 { _id: 2021, count: 4 },
 { _id: 2020, count: 3 },
 { _id: 2022, count: 3 } 
]

Example 2: In this example, We have established a database connection using mongoose and defined model over userSchema, having two columns or fields “name”, and “bornYear”. At the end, we are calling aggregate() method on User model and passing pipeline object with $sorByCount  as a key and $bornYear which is field in MongoDB collection as a value.

Database Structure: The database structure will look like this, the following documents are present in the collection.

 

Filename: app.js

Javascript




// Require mongoose module
const mongoose = require("mongoose");
  
// Set Up the Database connection
    useNewUrlParser: true,
    useUnifiedTopology: true,
});
  
const userSchema = new mongoose.Schema({
    name: String,
    bornYear: Number
});
  
const User = mongoose.model('User', userSchema);
  
User.aggregate([{ $sortByCount: "$bornYear" }])
    .exec((error, result) => {
        if (error) {
            console.log(error)
        } else {
            console.log(result);
        }
    })


Step to run the program: To run the application execute the below command from the root directory of the project:

node app.js

Output:

[
  { _id: 2000, count: 3 },
  { _id: 2019, count: 2 },
  { _id: 2021, count: 2 },
  { _id: 2018, count: 1 } 
]

Reference: https://mongoosejs.com/docs/api/aggregate.html#aggregate_Aggregate-sortByCount


My Personal Notes arrow_drop_up
Related Articles

Start Your Coding Journey Now!