代码之家  ›  专栏  ›  技术社区  ›  Ohjay44

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

  •  5
  • Ohjay44  · 技术社区  · 9 年前

    我正在使用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);
    });
    

    这可以在一个聚合查询中完成,还是需要拆分为两个?

    1 回复  |  直到 4 年前
        1
  •  3
  •   Ohjay44    9 年前

    可以在单个查询中执行此操作。

    您可以使用投影筛选的阵列 $project 分为两个不同的字段:一个是内容字段,另一个是计数字段。

    你可以使用 $slice

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