Ohj*_*y44 5 javascript mongodb node.js aggregation-framework mongodb-aggregation
我正在使用mongodb作为节点,我正在尝试根据一些设置过滤器聚合一组文档,然后将其限制为10.我将它聚合得很好并且限制很好但是我需要在之前获得聚合文档的总数我把它们限制在10.
这是我的代码.
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);
});
Run Code Online (Sandbox Code Playgroud)
这可以在一个聚合查询中完成,还是需要拆分为两个?
可以在单个查询中完成此操作。
您可以将过滤后的数组投影$project到两个不同的字段中:一个包含内容,另一个包含计数。
您可以使用$slice来限制内容数组。
db.collection.aggregate([
{
$match: {} // Filter
},
{
$group: {
_id: 1,
array: {$push: '$$ROOT'}
}
},
{
$project: {
content: {
$slice: ['$array', skip, limit]
},
total: {
$size: '$array'
}
}
}
], {allowDiskUse: true})
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
298 次 |
| 最近记录: |