[英]How do I get the total number of records before I run limit when using Aggregation
How do I get the total number of records before I run limit when using Aggregation?使用聚合时如何在运行限制之前获取记录总数?
stage 1阶段1
{
$text: {
$search: 'blah',
$caseSensitive: false
}
What can i do here to get the total number of records, so I can return as part response.我可以在这里做什么来获取记录总数,以便我可以作为部分响应返回。
stage 3第三阶段
{
$limit : 50
}
This would be a hack.这将是一个黑客。 As far as i understand your requirement, you need to get the count of total matching records before limiting them.
据我了解您的要求,您需要在限制它们之前获得总匹配记录的数量。
You can do this with below aggregation pipeline.您可以使用以下聚合管道执行此操作。
db.session.aggregate([{'$match':{'some-field':'some-value'}}, {'$group':{'_id':null, 'records':{'$push':'$$ROOT'}}}, {'$project':{'records':1, 'total_records':{'$size':'$records'}}}, {'$unwind':'$records'}, {'$limit':1}],{allowDiskUse:true}) db.session.aggregate([{'$match':{'some-field':'some-value'}}, {'$group':{'_id':null, 'records':{'$push' :'$$ROOT'}}}, {'$project':{'records':1, 'total_records':{'$size':'$records'}}}, {'$unwind':'$records '}, {'$limit':1}],{allowDiskUse:true})
total_records field will be the total matching documents count. total_records 字段将是总匹配文档数。 And Don't forgot to pass allowDiskUse parameter.
并且不要忘记传递 allowDiskUse 参数。 You might also need to use intermittent projection stage to alter documents as per your need.
您可能还需要使用间歇性投影阶段根据需要更改文档。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.