When to use an aggregation pipeline instead of JavaScript

If the answer is a number and the input is documents, the database should be doing the work.