MongoDB’s pipeline aggregation is – like most things in application development these days – confusing as hell (let’s be honest). Writing database queries using JavaScript’s object literal syntax is frightening, and quite frankly ridiculous. But here we are using it anyway, so we might as well know how to do one of the most useful database operations out there: a query across a collection that returns us a COUNT of the total results and a PORTION of the total results. Discovering how to do this in Mongo was crucial for us so that we could get ag-grid‘s virtual pagination to play nice! Now we can share the wisdom to the world in this blog post so that 1) others don’t pull their hair out figuring this out and 2) we don’t forget it.

So here’s a quick run down of how you can lookup (populate in mongoose vernacular), match (aka filter), sort, count, and limit using Mongo’s aggregation pipeline. And…. breathe.

Heads up: function calls in this example are to mongoose.

/**
* Query blog posts by user -> paginated results and a total count.
* @param userId {ObjectId} ID of user to retrieve blog posts for
* @param startRow {Number} First row to return in results
* @param endRow {Number} Last row to return in results
* @param [filter] {Object} Optional extra matching query object
* @param [sort] {Object} Optional sort query object
* @returns {Object} Object -> `{ rows, count }`
*/
function queryBlogPostsByUser (userId, startRow, endRow, filter = {}, sort = false) {
if (!(user instanceof mongoose.Types.ObjectId)) {
throw new Error('userId must be ObjectId')
} else if (typeof startRow !== 'number') {
throw new Error('startRow must be number')
} else if (typeof endRow !== 'number') {
throw new Error('endRow must be number')
} const query = [
// more lookups go here if you need them
// we have a many-to-one from blogPost -> user
{ $lookup: {
from: 'users',
localField: 'user',
foreignField: '_id',
as: 'user'
} },
// each blog has a single user (author) so flatten it using $unwind
{ $unwind: '$user' },
// filter the results by our userId
{ $match: Object.assign({ 'user._id': userId }, filter) }
] if (sort) {
// maybe we want to sort by blog title or something
query.push({ $sort: sort })
} query.push(
{ $group: {
_id: null,
// get a count of every result that matches until now
count: { $sum: 1 },
// keep our results for the next operation
results: { $push: '$$ROOT' }
} },
// and finally trim the results to within the range given by start/endRow
{ $project: {
count: 1,
rows: { $slice: ['$results', startRow, endRow] }
} }
) return BlogPost
.aggregate(query)
.then(([{ count, rows }]) => ({ count, rows }))
}

来源: https://outlandish.com/blog/tutorial/pagination-using-mongo-lookup-match-sort-count-and-limit-with-the-aggregation-pipeline/

使用Mongo进行分页的更多相关文章

  1. CentOS7.5安装MongoDB4.0与CRUD基本操作

    一 MongoDB简介 MongoDB 是一个基于分布式文件存储的数据库.由 C++ 语言编写.旨在为 WEB 应用提供可扩展的高性能数据存储解决方案. MongoDB 是一个介于关系数据库和非关系数 ...

  2. 解决mongodb查询慢的问题

    最近项目上一直在用mongodb作为数据库,mongodb有他的优势,文档型类json格式存储数据,修改起来比传统的关系型数据库更方便,但是最近在用mongodb出现了查询缓慢的问题,我用命令行查询, ...

  3. mongo中的分页查询

    /** * @param $uid * @param $app_id * @param $start_time * @param $end_time * @param $start_page * @p ...

  4. mongo数据排序和分页显示

    数据排序 使用sort()1 升序-1 降序自然排序 数据插入的顺序$natural db.stu.drop(); db.stu.insert({,,"address":" ...

  5. MongoDB 分页查询的方法及性能

    最近有点忙,本来有好多东西可以总结,Redis系列其实还应该有四.五.六...不过<Redis in Action>还没读完,等读完再来总结,不然太水,对不起读者. 自从上次Redis之后 ...

  6. Lind.DDD.Repositories.Mongo层介绍

    回到目录 之前已经发生了 大叔之前讲过被仓储化了的Mongodb,而在大叔开发了Lind.DDD之后,决定把这个东西再搬到本框架的仓储层来,这也是大势所趋的,毕竟mongodb是最像关系数据库的NoS ...

  7. MongoDB学习笔记~为IMongoRepository接口添加分页取集合的方法

    回到目录 对于数据分页,我们已经见的太多了,几乎每个列表页面都要用到分页,这已经成了一种定理了,在进行大数据展示时,如果不去分页,而直接把数据加载到内存,这简直是不可以去相向的,呵呵,在很多ORM工具 ...

  8. [MongoDB]Mongo基本使用:

    汇总: 1. [MongoDB]安装MongoDB2. [MongoDB]Mongo基本使用:3. [MongoDB]MongoDB的优缺点及与关系型数据库的比较4. [MongoDB]MongoDB ...

  9. mongo基本操作

    创建数据库文件的存放位置,比如d:/mongodb/data/db.启动mongodb服务之前需要必须创建数据库文件的存放文件夹,否则命令不会自动创建,而且不能启动成功. 打开cmd(windows键 ...

随机推荐

  1. php中的echo 与print 、var_dump 的区别

    ·  echo - 可以输出一个或多个字符串 ·  print - 只允许输出一个字符串,返回值总为 1 提示:echo 输出的速度比 print 快, echo 没有返回值,print有返回值1. ...

  2. Acrobat Pro DC 2019 mac中文版(pdf编辑器)

    为大家准备了最新版本的Adobe Acrobat Pro DC 2019 for Mac,这是Adobe官方推出的pdf编辑器,acrobat pro dc 2019破解版可以轻松将扫描件.图像.网页 ...

  3. js中filter的用法

    filter也是一个常用的操作,它用于把Array的某些元素过滤掉,然后返回剩下的元素. 和map()类似,Array的filter()也接收一个函数.和map()不同的是,filter()把传入的函 ...

  4. ReLU激活函数的缺点

    训练的时候很”脆弱”,很容易就”die”了,训练过程该函数不适应较大梯度输入,因为在参数更新以后,ReLU的神经元不会再有激活的功能,导致梯度永远都是零. 例如,一个非常大的梯度流过一个 ReLU 神 ...

  5. 2018-2019-2 网络对抗技术 20165321 Exp4 恶意代码分析

    1.实践目标 1.1是监控你自己系统的运行状态,看有没有可疑的程序在运行. 1.2是分析一个恶意软件,就分析Exp2或Exp3中生成后门软件:分析工具尽量使用原生指令或sysinternals,sys ...

  6. DDD关键知识点整理汇总

    创建领域对象采用构造函数或者工厂,如果用工厂时需要依赖于领域服务或仓储,则通过构造函数注入到工厂: 一个聚合是由一些列相联的Entity和Value Object组成,一个聚合有一个聚合根,聚合根是E ...

  7. C#中的委托(delegate)(个人整理)

    Delegate 一.什么是委托? 委托是一种引用类型,它是函数指针的托管版本.在C#中,委托是一种可以把引用存储为函数的类型.委托可以引用实例和静态方法,而函数指针只能引用静态方法.委托的声明非常类 ...

  8. idea用到的快捷键

    之前一直用的eclipse,早就听说idea更智能,更便捷,于是,下载了idea,然后再破解,现在就慢慢抛弃eclipse,平时就用idea进行编码. idea的快捷键与eclipse还是有较大不同, ...

  9. python selenium 百度登录

    from selenium import webdriver import time driver = webdriver.Chrome() driver.get("https://www. ...

  10. 《AI算法工程师手册》

    本文转载自:http://www.huaxiaozhuan.com/ 这是一份机器学习算法和技能的学习手册,可以作为学习工作的参考,都看一遍应该能收获满满吧. 作者华校专,曾任阿里巴巴资深算法工程师, ...