This question already has an answer here:
Implementing pagination in mongodb
                            
                                (1个答案)
                            
                    
                去年关闭。
        

    

我有一个包含100条记录的MongoDB集合,在NodeJ中,我想作为10条记录来检索,每条包含10条记录,我该怎么做

最佳答案

如果您希望记录是不同的,则可以使用Set对象来帮助您。该函数带有一个获取项键的函数,因此我们知道如何区分它们。

function groupByDistinct(records, groupSize, getKey) {
    const set = new Set();
    let result = [], current = [];
    for (let i = 0, l = records.length; i < l; i++) {
        const value = records[i], key = getKey(value);
        if (set.has(key) {
            continue;
        }
        set.add(key);
        current.push(value);
        if (current.length === groupSize) {
            result.push(current);
            current = [];
        }
    }
    if (current.length !== 0) {
        result.push(current);
    }
    return result;
}


用法示例

groupByDistinct(records, 10, x => x.key);

10-06 00:48