简体   繁体   English

当前聚合的MongoDB节点驱动程序计数

[英]MongoDB Node Driver Count of current aggregation

I am using mongodb for node and am trying to aggregate a collection of documents based on some set filters and then limit it to 10. I have it aggregating just fine and limiting just fine but I need to get the total number of that aggregated documents before I limit them to 10. 我正在为节点使用mongodb,并尝试基于一些设置的过滤器聚合文档集合,然后将其限制为10个。我对其进行了很好的汇总并进行了很好的限制,但是我需要先获取该汇总文档的总数我限制为10个。

Here is my code. 这是我的代码。

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);
});

Can this be done in one aggregation query or does it need to be split into two? 可以在一个聚合查询中完成此操作,还是需要将其拆分为两个?

It's possible to do so in a single query. 可以在单个查询中执行此操作。

You can project the filtered array using $project into two different fields: one with the content and one with the count. 您可以使用$project project将过滤后的数组$project到两个不同的字段中:一个带有内容,另一个带有count。

You can use $slice to limit the content array. 您可以使用$slice限制内容数组。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM