Mongoose prototype.Aggregate() API
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.
- pipeline: It is an array that is an aggregation pipeline as an array of objects.
- model: It is a method to use with this aggregate.
Setting up Node.js application:
Step 1: Create a Node.js application using the following command:
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 document with marks greater than 87.
Example 2: In this example, we are using the count pipeline inside the asynchronous function to count the matched document inside the collection.
Please Login to comment...