5

我正在使用mongodb作爲節點,並試圖根據一些設置的過濾器來聚合文檔的集合,然後將其限制爲10個。我把它聚合得很好,限制得很好,但我需要在將它們限制爲10之前獲得該彙總文檔的總數。MongoDB節點驅動程序當前聚合的計數

這是我的代碼。

var qry = []; 
if (filter.FocusArea && filter.FocusArea != "(None)") { 
    qry.push({ 
     $match: { 'ProgramAreaId': filter.FocusArea } 
    }); 
} 
if (filter.Status && filter.Status != "(None)") { 
    qry.push({ 
     $match: { 'StatusId': filter.Status } 
    }); 
} 
if (filter.ProgOfficer && filter.ProgOfficer != "(None)") { 
    qry.push({ 
     $match: { 'ProgramOfficerId': filter.ProgOfficer } 
    }); 
} 
if (filter.Fund && filter.Fund != "(None)") { 
    qry.push({ 
     $match: { 'FundId': filter.Fund } 
    }); 
} 
var skipNbr = (parseInt(filter.Page) * 10 - 10); 
qry.push({ $project: { _id: '$_id', count: { $sum: '$$ROOT' }, content: '$$ROOT'} }) // I would like to do the count here. 
qry.push({ $skip: skipNbr }) 
qry.push({ $limit: 10 }) 
var apps = mongo.collection('Applications').aggregate(qry, function(err, docs) { 
    callback(docs); 
}); 

這可以在一個聚合查詢中完成,還是需要分成兩個?

回答

2

可以在單個查詢中這樣做。

您可以使用$project將已過濾的數組投影到兩個不同的字段中:一個包含內容,另一個包含計數。可以使用$slice來限制內容數組。

db.collection.aggregate([ 
    { 
     $match: {} // Filter 
    }, 
    { 
     $group: { 
      _id: 1, 
      array: {$push: '$$ROOT'} 
     } 
    }, 
    { 
     $project: { 
      content: { 
       $slice: ['$array', skip, limit] 
      }, 
      total: { 
       $size: '$array' 
      } 
     } 
    } 
], {allowDiskUse: true}) 
+0

$ array是一個mongo屬性還是你說的東西在這個地方? – Ohjay44

+0

這是來自您的收藏的項目數組。查看更新後的答案。 –

+0

我想你可能誤解了這個問題。我試圖在彙總後但在限制之前對我的收藏中的所有文檔進行計數。我沒有處理文檔中的嵌套數組。 – Ohjay44