[SERVER-54958] Empty result when counting from empty collection in aggregation Created: 04/Mar/21 Updated: 31/Aug/23 |
|
| Status: | Backlog |
| Project: | Core Server |
| Component/s: | Aggregation Framework |
| Affects Version/s: | 4.4.4 |
| Fix Version/s: | None |
| Type: | Bug | Priority: | Major - P3 |
| Reporter: | Maël Jaquier | Assignee: | Backlog - Query Optimization |
| Resolution: | Unresolved | Votes: | 0 |
| Labels: | None | ||
| Remaining Estimate: | Not Specified | ||
| Time Spent: | Not Specified | ||
| Original Estimate: | Not Specified | ||
| Issue Links: |
|
||||||||||||||
| Assigned Teams: |
Query Optimization
|
||||||||||||||
| Operating System: | ALL | ||||||||||||||
| Steps To Reproduce: | Example with "live" collection not empty:
Example with empty "live" collection:
|
||||||||||||||
| Participants: | |||||||||||||||
| Description |
|
Hi, During an aggregation, we need to count the number of elements matching a specific rule. It works properly most of the time, however when there is no matching document (or the collection itself is empty), we get an empty result instead of a document with count equal to 0. We understand this is probably a optimization to avoid processing stages on empty result, however operation such as count should probably be computed anyway in order to produce a consistent result. The reason why we want to apply count inside aggregation instead of the aggregation result is because we would like to apply MongoDB expression evaluation on it (i.e. {count: { $eq: 20 }} for example). |
| Comments |
| Comment by Charlie Swanson [ 16/Mar/21 ] | ||||||||||||||||||||||||||||||||||||||||||||||||||||||
|
Hi mael.jaquier@swissdotnet.ch, As you can see here, this is happening because $count is simply an alias for $group - shown in the explain output. $group's behavior was considered in | ||||||||||||||||||||||||||||||||||||||||||||||||||||||
| Comment by Edwin Zhou [ 08/Mar/21 ] | ||||||||||||||||||||||||||||||||||||||||||||||||||||||
|
Hi mael.jaquier@swissdotnet.ch, Thanks for your detailed improvement request. When running aggregate on an empty collection, you're correct in that the planner attempts to optimize the execution, and the executionStats show that the winning plan uses an EOF stage.
I can understand your use case in returning a count of 0 when using $count in a pipeline on an empty collection. We'll assign this to the appropriate team to be evaluated against our currently planned work. Updates will be posted on this ticket as they happen. Best, |