[SERVER-15611] Support returning both the matched documents and the count of matched documents in the aggregation framework Created: 13/Oct/14  Updated: 31/Jul/19  Resolved: 31/Jul/19

Status: Closed
Project: Core Server
Component/s: Aggregation Framework
Affects Version/s: None
Fix Version/s: None

Type: New Feature Priority: Major - P3
Reporter: Linda Qin Assignee: Charlie Swanson
Resolution: Duplicate Votes: 1
Labels: expression
Remaining Estimate: Not Specified
Time Spent: Not Specified
Original Estimate: Not Specified

Issue Links:
Depends
Duplicate
duplicates SERVER-23654 Add $facet aggregation stage Closed
Related
is related to SERVER-12927 Support ROLLUP function in the $group... Backlog
Sprint: Query 2019-08-12
Participants:

 Description   

Currently, we can compute a count of the documents using the following aggregation pipelines:

However, with this pipeline, we won't be able to get all the matched documents. It would be nice if we can get both the matched documents and the count of the matched documents in one aggregation command.



 Comments   
Comment by Charlie Swanson [ 31/Jul/19 ]

This can be achieved by using the $facet aggregation stage, so I'm closing this ticket as a duplicate of SERVER-23654. Note that in the general case we may need to implement a solution to SERVER-24804, which is tracked separately.

Comment by Scott Hernandez (Inactive) [ 30/Oct/14 ]

Can you please expand on what this would look like, both in terms of your use cases and expected output?

Comment by Thomas Rueckstiess [ 13/Oct/14 ]

In versions 2.6 and above, this can be achieved with the $$ROOT special operator (e.g. see this example in the documentation), that allows access to the full document. Here is an example for the $group stage that would return the count and an array of matched documents:

db.articles.aggregate(
    // Assume indexed $match & $project pipeline stages to appropriate limit output
    { $group: {
        _id: null,
        count: { $sum: 1 },
        docs: { $push: "$$ROOT" },
    }}
)

The caveat is that the resulting document need to fit within the limits of a 16MB BSON document.

Generated at Thu Feb 08 03:38:30 UTC 2024 using Jira 9.7.1#970001-sha1:2222b88b221c4928ef0de3161136cc90c8356a66.