使用聚合以及跳过并限制时,获取总文档的数量
在下面的查询中,使用limep
skip 时,如何获得文档的总数?
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)
在这里,我始终将文档限制为limit
,但是在每个查询中,我也想知道总文档。我该怎么做?
编辑 虽然你们中有些人建议使用$ facet
,但我不确定如何使用。例如,汇总返回50
文档无限。我如何使用$ facet
,以便它不仅返回limit
文档,而且还返回包含总文档的元数据。
这是一个工作查询,来自 mongodb playground 我创建了。我如何使用$ facet
或任何其他方法来获取总数。
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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
一个选项是使用
$ facet
,但缺点是它将您的所有文档分组到一个文档中:另一个选项是使用
$ setWindowfields
将总数添加到每个文档,可以将它们保留为单独的文档:One option is using
$facet
, but the disadvantage is that it will group all your documents to one document:Other option is to use
$setWindowFields
to add the total count to each document, which allows to keep them as separate documents: