How to run aggregation pipeline in Mongodb compass?

Using mongodb compass to run aggregation pipeline written in Node.js

If you have a JSON-serialized aggregation pipeline that you want to use in the aggregation tab of MongoDB Compass, you can follow these steps:

  1. Generate the Aggregation Pipeline in Node.js:

    Use your Node.js code to generate the aggregation pipeline. Serialize it into a JSON string using JSON.stringify. For example:

     const aggregationPipeline = [
       { $match: { status: 'active' } },
       { $group: { _id: '$category', total: { $sum: '$quantity' } } }
     ];
    
     const serializedPipeline = JSON.stringify(aggregationPipeline);
    

    serializedPipeline will be your JSON-serialized aggregation pipeline.

  2. Copy the Serialized Pipeline:

    Copy the value of serializedPipeline.

  3. Open MongoDB Compass:

    Launch MongoDB Compass and connect to your MongoDB server or cluster.

  4. Navigate to Your Collection:

    In Compass, navigate to the collection on which you want to run the aggregation.

  5. Click on the Aggregations Tab:

    Inside the collection view, click on the "Aggregations" tab. This will open the aggregation pipeline editor.

  6. Paste the Serialized Pipeline:

    In the editor, simply paste the JSON-serialized aggregation pipeline that you copied earlier.

  7. Click "Run":

    After pasting, click the "Run" button to execute the aggregation.

By pasting the JSON-serialized pipeline directly into MongoDB Compass, you can run the aggregation without manually constructing it in the GUI. Remember to validate the pipeline to ensure it produces the desired results. This approach is particularly useful when you have complex pipelines generated programmatically.