MongoDB - Aggregation Framework (Total Count)

后端 未结 7 1927
余生分开走
余生分开走 2020-12-31 07:42

When running a normal \"find\" query on MongoDB I can get the total result count (regardless of limit) by running \"count\" on the returned cursor. So, even if I limit to re

7条回答
  •  时光取名叫无心
    2020-12-31 08:42

    Assaf, there's going to be some enhancements to the aggregation framework in the near future that may allow you to do your calculations in one pass easily, but right now, it is best to perform your calculations by running two queries in parallel: one to aggregate the #posts for your top authors, and another aggregation to calculate the total posts for all authors. Also, note that if all you need to do is a count on documents, using the count function is a very efficient way of performing the calculation. MongoDB caches counts within btree indexes allowing for very quick counts on queries.

    If these aggregations turn out to be slow there are a couple of strategies. First off, keep in mind that you want start the query with a $match if applicable to reduce the result set. $matches can also be speed up by indexes. Secondly, you can perform these calculations as pre-aggregations. Instead of possible running these aggregations every time a user accesses some part of your app, have the aggregations run periodically in the background and store the aggregations in a collection that contains pre-aggregated values. This way, your pages can simply query the pre-calculated values from this collection.

提交回复
热议问题