繁体   English   中英

如何使用 mongodb 聚合进行分页?

[英]How to do pagination with a mongodb aggregate?

在 MongoDB 上工作时,我在做 Pagination 时遇到了问题。当我尝试将 Paginaiton 与 aggerate 包含在一起时。我也试图在其中包含facets

我的代码:仅用于搜索

app.get("/search", async(req, res) => {
    try {
        const text = req.query.text

      let result = await collection.aggregate([                    
            {
                '$search': {
                    'text': {
                        'query': `${text}`,
                        'path': 'title'
                    }
                }
            }
        ]).toArray();
        res.send(result)
    } catch (error) {
       console.error(error)
    }
})

这适用searchpagination 像这样,看,它不需要任何可选的request.query.page

http://localhost:4000/search?text=mango
http://localhost:4000/search?text=mango?page=1


现在,我还想在pagination搜索中包含pagination ......所以,

server.get("/search", async(req, res) => {
    try {
        const key = req.query.key;
        const value = req.query.value; 
        const text = req.query.text;
        const page = req.query.page; //Page query create

    let result = await collection.aggregate([                    
            {
                '$search': {
                    'text': {
                        'query': `${text}`,
                        'path': 'title'
                    }
                }
            },
            {
                '$match': {
                    [key]: `${value}`
                }
            }
        ]).toArray();
        res.send(result)

    } catch (error) {
       console.error(error)
    }
})

为此工作没有页数

http://localhost:4000/search?text=Mango&key=Brand&value=rasna

不适用于分页

http://localhost:4000/search?text=Mango&key=Brand&value=rasna&page=2

我错在哪里? 我是否需要创建任何附加function才能使其正常工作或其他功能?

您可以同时使用 $skip 和 $limit 聚合管道来实现此目的。 假设我们希望每页只有 20 个项目。 所以我们的代码是这样的:

    server.get("/search", async(req, res) => {
    try {
        const key = req.query.key;
        const value = req.query.value; 
        const text = req.query.text;
        const page = req.query.page - 1; //We subtract one because we don't want skip first twenty items in first page

    let result = await collection.aggregate([                    
            {
                '$search': {
                    'text': {
                        'query': `${text}`,
                        'path': 'title'
                    }
                }
            },
            {
                '$match': {
                    [key]: `${value}`
                }
            },
            { $skip: page * 20 },
            { $limit: 20 }
        ]).toArray();
        res.send(result)

    } catch (error) {
       console.error(error)
    }
})

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM