How can I get the total count of documents when using the aggregation along with limit and skip like in the following query?
db.Vote.aggregate({
$match: {
tid: "e6d38e1ecd",
"comment.topic": {$exists: 1},
}
},{
$group: {
_id: {
topic: "$comment.topic",
text_sentiment: "$comment.text_sentiment"
},
total: {$sum: 1},
}
},{
$project: {
topic: {
name: "$_id.topic",
occurence: "$total"
},
sentiment: "$_id.text_sentiment"
}
},{
$sort: {"topic.occurence": -1}
})
.skip(SKIP)
.limit(LIMIT)
Here I would always get the documents bounded by LIMIT, but at each query, I also want to know the total documents. How can I do that?
EDIT
While some of you have suggested using $facet, I am not sure how to use that. For example, the aggregation returns 50 documents without limit. How can I use $facet such that it not only returns LIMIT documents but also the meta-data that contains the total documents.
Here is a working query from MongoDB Playground that I created. How can I use $facet or any other method to get the total count.
One option is using $facet, but the disadvantage is that it will group all your documents to one document:
db.Vote.aggregate(
{$match: {tid: "e6d38e1ecd", "comment.topic": {$exists: 1}}},
{$group: {_id: {topic: "$comment.topic", text_sentiment: "$comment.text_sentiment"},
total: {$sum: 1}}
},
{$project: {topic: {name: "$_id.topic", occurence: "$total"},
sentiment: "$_id.text_sentiment"}
},
{$facet: {
data: [{$sort: {"topic.occurence": -1}}, {$skip: SKIP}, {$limit: LIMIT}],
total: [{ $count: "total" }]
}}
)
Other option is to use $setWindowFields to add the total count to each document, which allows to keep them as separate documents:
db.Vote.aggregate(
{$match: {tid: "e6d38e1ecd", "comment.topic": {$exists: 1}}},
{$group: {_id: {topic: "$comment.topic", text_sentiment: "$comment.text_sentiment"},
total: {$sum: 1}}
},
{$project: {topic: {name: "$_id.topic", occurence: "$total"},
sentiment: "$_id.text_sentiment"}
},
{
$setWindowFields: {output: {totalCount: {$count: {}}}}
})
.skip(SKIP)
.limit(LIMIT)