在 MongoDB 集合中查找前 20 个文档。

7

我希望在一个Jframe上显示集合中的前20条记录,并在另一个框架上显示下20条记录。我是MongoDB的新手,请建议一个查询以查找前20个和下一个20个文档。

3个回答

17

我认为对于大型集合来说,这个速度比较慢是因为mongodb索引数据的方式?所以你应该使用基于时间戳范围的范围查询来获得更好的性能?例如,下一个小时、下一天等。 - kenyee
@kenyee,如果你能做到那样,那会更好,但在每种情况下都几乎不可能。 - Derick

3
db.getCollection('name of your collection').find({}).limit(20)

1
这是我到目前为止所取得的成就。
function getFirst20Items() {
    let items

    ITEMS_COLLECTION
        .find({})
        .limit(20)
        .sort({id: 1})
        .toArray( (err, allItems) => {
            items = allItems
        })

    return new Promise(resolve => {
        setTimeout(() => {
            resolve(items)
        }, 2000)
    })
}

function getSecond20Items() {
    let items

    ITEMS_COLLECTION
         // gte stands for --> Greater than
        .find({ id: { $gte: 20 } })
        .limit(20)
        .sort({id: 1})
        .toArray( (err, allItems) => {
            items = allItems
        })

    return new Promise(resolve => {
        setTimeout(() => {
            resolve(items)
        }, 2000)
    })
}

app.get('/first/40/products', (req, res) => {
    const all_Items = []

    getFirst20Items()
        .then(items => {
            all_Items.push(...items)
        })
        .catch(err => {
            throw new CustomError('Could not get Items', err);
        });
    getSecond20Items()
        .then(items => {
            all_Items.push(...items)
        })
        .catch(err => {
            throw new CustomError('Could not get Items', err);
        });
    setTimeout(() => {
        res.send(all_Items);    
    }, 2000);
});

你可以从这里开始继续编写你的逻辑

希望这有所帮助


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接