QA
Senior LevelMongoDB & Mongoose

How do you write Custom Aggregation Expressions ($accumulator and $function) in JavaScript?

❓ Interview Prompt: Explain $accumulator and $function stages, executing inline JavaScript logic in aggregation pipelines, and performance trade-offs.

The '$accumulator' stage allows executing custom JavaScript init, accumulate, merge, and finalize functions directly inside aggregation pipelines when native stages lack required logic.

Code Implementation Example

typescript
import { OrderModel } from './models/Order';

async function customJavaScriptAccumulator() {
  return await OrderModel.aggregate([
    {
      $group: {
        _id: '$category',
        customSum: {
          $accumulator: {
            init: 'function() { return 0; }',
            accumulate: 'function(state, value) { return state + value; }',
            accumulateArgs: ['$price'],
            merge: 'function(state1, state2) { return state1 + state2; }',
            finalize: 'function(state) { return state; }',
            lang: 'js'
          }
        }
      }
    }
  ]);
}
💡Writing custom JavaScript aggregation accumulators via $accumulator.
🎯 Interview Key Takeaway

Use $accumulator for complex custom aggregation math when native aggregation operators are insufficient.

#$accumulator#$function#Custom Aggregation#Senior
Back to all MongoDB & Mongoose Questions→

More MongoDB & Mongoose Interview Questions

Beginner LevelMongoDB & Mongoose

How does the MongoDB Aggregation Pipeline work? Explain $match, $group, $lookup, and $project.

Beginner LevelMongoDB & Mongoose

What is MongoDB and how does the BSON document data model work?

Beginner LevelMongoDB & Mongoose

What is the structure of a MongoDB ObjectId and how is it generated?