MongoDB聚合:将文档分成大小相等的窗口/块

erhoui1w  于 2023-01-20  发布在  Go
关注(0)|答案(1)|浏览(90)

我正在执行MongoDB聚合以从现有集合创建新集合,并且正在努力寻找一种按计数而不是按值对元素进行分组的方法。
我想实现这样的目标:
数据:

[
    {"_id": "my_id_0"},
    {"_id": "my_id_1"},
    {"_id": "another_id"},
    {"_id": "another_id_123"},
    {"_id": "_id"},
    {"_id": "document_id"},
    {"_id": "document_id_1"},
    {"_id": "document_id_2"},
    {"_id": "document_id_3"},
    {"_id": "document_id_4"},
]

查询

db.coll.aggregate([
    {
        $someNonExistingStage: {
            output: {
                chunk: {"$push": "$_id"}
            },
            n: 3
        }
    }
])

结果:

[
    {"chunk": ["my_id_0", "my_id_1", "another_id"]},
    {"chunk": ["another_id_123", "_id", "document_id"]},
    {"chunk": ["document_id_1", "document_id_2", "document_id_3"]},
    {"chunk": ["document_id_4"]},
]

我想要的块的实际长度大约是1024
我想也许可以使用bucketAuto或setWindowFields来实现,但看起来我应该先枚举所有文档,这一点并不清楚。
先谢了。

mspsb9vt

mspsb9vt1#

在这个场景中,数据库实际上并没有为您做任何事情。我们既没有过滤文档,也没有对文档进行分组,以减少从集合中提取并传输到客户端的材料数量,我们也没有利用索引。我们还不如在客户端运行一个循环:

function vendChunk(cursor, size) {
    var chunk = [];
    for(var i = 0; i < size; i++) {
        if(!cursor.hasNext()) {
            break;
        }
        chunk.push(cursor.next());
    }
    return chunk;
}

c = db.foo.find(); // or find(predicate) if desired...

while(1) {
    var chunk = vendChunk(c, 4);
    if(chunk.length == 0) {
        break;
    }
    print("chunk: ", chunk);
}

相关问题