简体   繁体   English

使用聚合时如何在运行限制之前获取记录总数

[英]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.

相关问题 如何从控制器获取固定装置中的记录总数? - How do I get the total number of records in a fixture from a controller? 在 JavaScript 中对 JSON 数据执行聚合。 我必须得到每所学校的记录总数和学校记录的总分 - Perform an aggregation on JSON data in JavaScript. I have to get the total number of Records for each school and total Marks of School Records 如何限制FireBase firestore get()方法返回的记录? - How do I limit records returned by FireBase firestore get() method? 如何仅获取一次变量中的对象总数? - How do I get total number of objects in a variable only once? 如何获取 RestAPI 响应中收到的总列数? - How do I get total number of columns received in RestAPI response? 我如何使用 jquery 将推文数量限制为一条 - how do i limit the number of tweets to one using jquery 如何让我的 for 循环在打印之前运行? - How do I get my for loop to run before it prints? 使用 qUnit 时如何在每次测试之前运行函数? - How do I run a function before each test when using qUnit? 如何限制图层中的多边形数量? - How do I limit the number of polygons in a layer? 使用mongo聚合如何获取带有计数的记录 - using mongo aggregation how to get records with count
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM