Mongoose,聚合与 Js 函数

Mongoose, Aggregation vs Js functions

我需要搜索我的 Mongo 数据库并获取一年中每个月的平均用户数。使用聚合直接通过数据库搜索来执行此操作是否更高效,或者我首先获取所有数据并使用基本的 javascript 函数(如 for、reduce、map ...)组织它们会更好吗?

简短的回答:MongoDB,因为是用 c++ 编写的,所以会比你的 JS 函数更有效率。

长答案:您可以阅读多篇文章或 Whosebug 问题,例如:

  • This baeldung article
  • What are the pros and cons of performing calculations in sql vs. in your application 问题
  • Which is Faster, MogoDB Aggregate or Self Implemented "For" Loop? 问题

从本质上讲,DB 进程比 JS 中的函数更优化,并且是使用聚合框架进行数学运算的更好选择。