【问题标题】:Pagination in Mongodb NodejsMongodb Nodejs中的分页
【发布时间】:2018-01-04 09:16:20
【问题描述】:

有什么方法可以获取查找操作中的文档总数以及 MongoDB 中查询中的跳过和限制

 MongoClient.connect(Config.dbURI, function (err, db) {
    if (!err) {
        console.log("We are connected");
        console.log(uniqueId)
        db.collection(dbName).find({'uniqueId': uniqueId, 'isDeleted': false})
            .sort({modifiedDateISO: -1})
            .limit(parseInt(limit))
            .skip(parseInt(limit * page))
            .toArray((errFindChat, dataFindChat) => {

                           console.log(errFindChat, dataFindChat);

     });
});

【问题讨论】:

  • 如果你使用的是猫鼬,你可以使用“mongoose-paginate”npmjs.com/package/mongoose-paginate
  • 我正在使用mongodb驱动
  • 不行,没有别的办法。应用两个查询。人们会说我们可以做我知道这也可以通过 map-reduce 来完成,但查询会比使用 2 个查询慢 10 倍。

标签: node.js mongodb pagination


【解决方案1】:

我假设“uniqueId”不是主键!

MongoClient.connect(Config.dbURI, function (err, db) {
   if (!err) {
       console.log("We are connected");
       console.log(uniqueId)
       db.collection("collname").aggregate(
            [
              { "$match":  { "uniqueId": uniqueId, 'isDeleted': false} },
              { "$count":  "total" }, 
              { "$sort" :  {"modifiedDateISO": -1 },
              { "$limit":  parseInt(limit) },
              { "$skip" :  parseInt(limit * page) }  
            ]

        ).toArray((errFindChat, dataFindChat) => {
              console.log(errFindChat, dataFindChat);
        });
    }
});

MongoDB Aggregate Count

【讨论】:

  • name: 'MongoError', message: 'Unrecognized pipeline stage name: \'$count\'', ok: 0, errmsg: 'Unrecognized pipeline stage name: \'$count\'',代码:16436 }
  • 我认为是因为版本。你可以试试这个而不是 $count 阶段{ "$group": {'_id': '$uniqueId' , 'total': { '$sum' : 1 } } }
  • @edam 的解决方案有效,页码应该从 0 开始。
【解决方案2】:
var query   = {}; // Your condition
var options = {
    select:   'title date author',
    sort:     { date: -1 },
    populate: 'author',
    lean:     true,
    offset:   20, 
    limit:    10
};

Book.paginate(query, options).then(function(result) {
    // ... 
});

猫鼬分页很好

【讨论】:

    【解决方案3】:

    如果您使用 .find..,则无法使用跳过和限制进行过滤,并且只能在一个请求中获得总数。

    如果您只想在一个请求中检索文档、过滤和执行计数操作,您必须使用aggregate

    db.coll.aggregate([
    {$match: your find conditions},
    {$group/project: your count operations, etc....},
    {$skip: skip}, // pagination skip
    {$limit: limit}, // pagination limit
    ...
    ]);
    

    【讨论】:

    • 您好,如何获取符合条件的文档总数?因为我需要在前端显示页码
    • 您必须单独查询数据库才能获得计数。
    • 有什么方法可以在同一个查询中获取计数
    猜你喜欢
    • 1970-01-01
    • 2021-08-16
    • 1970-01-01
    • 1970-01-01
    • 2020-09-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多