首页 > 解决方案 > 如何在聚合命令期间跳过前 n 个批处理文档?

问题描述

我运行这个命令:

db.runCommand( 

  {
    aggregate:"myColl",
    pipeline:[
      {
        $group:{
          _id:{_id:"$_id"},
          count:{$sum:NumberInt(1)}}
      }
    ],
    cursor:{}
  }

 )

它给我的回报是:

{ 
    "cursor" : {
        "firstBatch" : [
            {
                "_id" : {
                    "_id" : NumberLong(-9223365602644598416)
                }, 
                "count" : 1.0
            }, 
            {
                "_id" : {
                    "_id" : NumberLong(-9223363178405875157)
                }, 
                "count" : 1.0
            }, 
            {
                "_id" : {
                    "_id" : NumberLong(-9223350896770545240)
                }, 
                "count" : 1.0
            }, 
            {
                "_id" : {
                    "_id" : NumberLong(-9223338355283447904)
                }, 
                "count" : 1.0
            }, 
            ....
        ], 
        "id" : NumberLong(4379399839731469797), 
        "ns" : "myDatabase.myColl"
    }, 
    "ok" : 1.0
}

现在我想向命令指示要跳过的批处理文档的数量以及要返回的批处理文档的数量。可能吗?

标签: mongodbmongodb-queryaggregation-framework

解决方案


你可以试试这个:

db.runCommand(

    {
        aggregate: "myColl",
        pipeline: [
            {
                $group: {
                    _id: { _id: "$_id" },
                    count: { $sum: NumberInt(1) }
                }
            },
            { $skip: n } // n should be a positive integer, where n documents are skipped
        ],
        cursor: { "batchSize": n } // n should be a number, it denotes the batch size.
    }
)

推荐阅读