Skip to content
This repository has been archived by the owner on Sep 21, 2022. It is now read-only.

Commit

Permalink
Merge pull request #81 from outgrow/outgrow-fix-totalCount-for-aggreg…
Browse files Browse the repository at this point in the history
…ates

Fix `totalCount` on `getPaginatedResponseFromAggregate`
  • Loading branch information
Akarshit authored Jun 8, 2021
2 parents 700bcee + df31453 commit 58817a8
Show file tree
Hide file tree
Showing 2 changed files with 74 additions and 4 deletions.
36 changes: 34 additions & 2 deletions lib/graphql/getPaginatedResponseFromAggregate.js
Original file line number Diff line number Diff line change
Expand Up @@ -39,11 +39,43 @@ async function getPaginatedResponseFromAggregate(collection, pipeline, args, {
let totalCount = null;
if (includeTotalCount) {
pipeline.push({
"$addFields": {
/**
* This stage gathers all of the objects that the pipeline has returned into a single array in one document.
* Because we have all the documents in a single array, we can now count them using $sum. Unfortunately the only
* way to count the number of returned objects with aggregates, as `.count()` is not available on aggregates.
*/
$group: {
_id: null,
objects: {
$addToSet: "$$ROOT"
},
totalCount: {
"$sum": 1
$sum: 1
}
}
}, {
/**
* Now that we've calculated the total count of objects, we can $unwind our array in our single object to get
* individual objects again.
*/
$unwind: {
path: "$objects"
}
}, {
/**
* Set `totalCount` inside of our objects, since we'll replace the root in the next stage.
*/
$set: {
"$objects.totalCount": "$totalCount"
}
}, {
/**
* Replace the root. We now have all the objects that were returned by the pipeline originally, but with a new
* `totalCount` field in each of them that contains the total count of objects returned.
*/
$replaceRoot: {
newRoot: "$objects"
}
});
}

Expand Down
42 changes: 40 additions & 2 deletions lib/graphql/getPaginatedResponseFromAggregate.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -56,12 +56,31 @@ test("includes sort param in pipeline and returns correct result", async () => {
"$someOperator": "someParameter"
},
{
"$addFields": {
"$group": {
_id: null,
objects: {
"$addToSet": "$$ROOT"
},
totalCount: {
"$sum": 1
}
}
},
{
$unwind: {
path: "$objects"
}
},
{
$set: {
"$objects.totalCount": "$totalCount"
}
},
{
$replaceRoot: {
newRoot: "$objects"
}
},
{
"$sort": "SORT"
},
Expand All @@ -84,12 +103,31 @@ test("returns totalCount == 0 when there are no documents", async () => {
"$someOperator": "someParameter"
},
{
"$addFields": {
"$group": {
_id: null,
objects: {
"$addToSet": "$$ROOT"
},
totalCount: {
"$sum": 1
}
}
},
{
$unwind: {
path: "$objects"
}
},
{
$set: {
"$objects.totalCount": "$totalCount"
}
},
{
$replaceRoot: {
newRoot: "$objects"
}
},
{
"$limit": 20
}
Expand Down

0 comments on commit 58817a8

Please sign in to comment.