[英]How to get the real count of matching documents when using limit in mongodb?
I have a facet aggregation in mongodb.我在 mongodb 中有一个方面聚合。 It works.
有用。 Now, I need to limit the result in order to have an infinite scroll.
现在,我需要限制结果才能无限滚动。 How to get the total count of matching documents in the entire collection?
如何获取整个集合中匹配文档的总数?
I can get the total count of documents in the collection, but this number is not relevant.我可以获得集合中文档的总数,但这个数字不相关。 My goal is to know if the user can fetch more data.
我的目标是知道用户是否可以获取更多数据。 If he has received 120 documents, but 150 matches his filter, then another query can be performed.
如果他收到了 120 个文档,但有 150 个与他的过滤器匹配,则可以执行另一个查询。
Here is my query:这是我的查询:
db.collection.aggregate([ { $facet: { data: [ { $match: { score: {$gt: 80 } } }, { $skip: 0}, { $limit: 2}, { $project: { score: 1 } } ], } }, ])
You can play with fake data in this sandbox: https://mongoplayground.net/p/EClbe0f_Fms您可以在此沙箱中使用假数据: https://mongoplayground.net/p/EClbe0f_Fms
The real number of matching documents is 4. If I add a "hits" after the facet with the $count operator, I receive 7, which the the total of documents.匹配文档的实际数量是 4。如果我在带有 $count 运算符的构面后添加一个“命中”,我会收到 7,即文档总数。 How to get this information in an efficient way?
如何有效地获取这些信息?
The most efficient way would be not to use $count at all but rather to check if the last page received was less than the limit.最有效的方法是根本不使用 $count,而是检查收到的最后一页是否小于限制。 Ie:
IE:
const perPage = 10;
const results = await getPageOfResults();
const atEnd = results.length < perPage;
It sound like you added $count to your facet already but got an incorrect result.听起来您已经将 $count 添加到您的方面,但结果不正确。 To get the 'real' number of matching documents you need to add the $match stage to both facets like so https://mongoplayground.net/p/liQaiyZhYER
要获得匹配文档的“真实”数量,您需要将 $match 阶段添加到两个方面,例如https://mongoplayground.net/p/liQaiyZhYER
db.collection.aggregate([
{
$facet: {
data: [
{ $match: { score: {$gt: 80 } } },
{ $skip: 0},
{ $limit: 2},
{ $project: { score: 1 } }
],
count: [
{ $match: { score: {$gt: 80 } } },
{ $count: 'total' }
]
}
},
{$unwind: "$count"},
{$addFields: {
count: "$count.total"
}}
])
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.