![]() |
VOOZH | about |
The API.prototype.Aggregate() method of the Mongoose API is used to build aggregation pipelines. Aggregation is a method of processing many documents by sending them through multiple phases.
Syntax:
Model.aggregate()
Parameters:
Returns: It returns plan JavaScript Objects.
Setting up Node.js application:
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:
Example 1: In this example, we have established a database connection using mongoose and defined a model over schema, having three columns or fields βnameβ, "marks" and βmobileβ. In the end, we are using the aggregate() method on the User model which will use match and filter some tuples of lists from the User collection.
Database Structure: The database structure will look like this, Three documents are present in the collection over which we match the document with marks greater than 87. In collection, we have only two documents with marks greater than 87.
Filename: app.js
Output:
Example 2: In this example, we are using the count pipeline inside the asynchronous function to count the matched document inside the collection.
Filename: script.js
Output:
Reference: https://mongoosejs.com/docs/api/mongoose.html#mongoose_Mongoose