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.