Is there a way to retrieve the total count of documents when implementing aggregation along with limit
and skip
in a query similar to the one below?
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)
While the above query enables me to retrieve documents within the specified LIMIT
, I am also interested in knowing the total count of documents each time I execute the query. How can I achieve this?
UPDATE
Although some have suggested utilizing $facet
, I'm uncertain about its implementation. For instance, if the aggregation fetches 50
documents unlimitedly, how can I incorporate $facet
to not only retrieve LIMIT
documents but also the metadata containing the total document count?
Referencing a functional query on MongoDB Playground that I crafted, how can I leverage $facet
or any other approach to obtain the total count?