簡體   English   中英

使用聚合時如何在運行限制之前獲取記錄總數

[英]How do I get the total number of records before I run limit when using Aggregation

使用聚合時如何在運行限制之前獲取記錄總數?

階段1

{
  $text: { 
    $search: 'blah', 
    $caseSensitive: false 
}

我可以在這里做什么來獲取記錄總數,以便我可以作為部分響應返回。

第三階段

{ 
  $limit : 50 
}

這將是一個黑客。 據我了解您的要求,您需要在限制它們之前獲得總匹配記錄的數量。

您可以使用以下聚合管道執行此操作。

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 字段將是總匹配文檔數。 並且不要忘記傳遞 allowDiskUse 參數。 您可能還需要使用間歇性投影階段根據需要更改文檔。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM