使用Mongo进行分页
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 }))
}
使用Mongo进行分页的更多相关文章
- CentOS7.5安装MongoDB4.0与CRUD基本操作
一 MongoDB简介 MongoDB 是一个基于分布式文件存储的数据库.由 C++ 语言编写.旨在为 WEB 应用提供可扩展的高性能数据存储解决方案. MongoDB 是一个介于关系数据库和非关系数 ...
- 解决mongodb查询慢的问题
最近项目上一直在用mongodb作为数据库,mongodb有他的优势,文档型类json格式存储数据,修改起来比传统的关系型数据库更方便,但是最近在用mongodb出现了查询缓慢的问题,我用命令行查询, ...
- mongo中的分页查询
/** * @param $uid * @param $app_id * @param $start_time * @param $end_time * @param $start_page * @p ...
- mongo数据排序和分页显示
数据排序 使用sort()1 升序-1 降序自然排序 数据插入的顺序$natural db.stu.drop(); db.stu.insert({,,"address":" ...
- MongoDB 分页查询的方法及性能
最近有点忙,本来有好多东西可以总结,Redis系列其实还应该有四.五.六...不过<Redis in Action>还没读完,等读完再来总结,不然太水,对不起读者. 自从上次Redis之后 ...
- Lind.DDD.Repositories.Mongo层介绍
回到目录 之前已经发生了 大叔之前讲过被仓储化了的Mongodb,而在大叔开发了Lind.DDD之后,决定把这个东西再搬到本框架的仓储层来,这也是大势所趋的,毕竟mongodb是最像关系数据库的NoS ...
- MongoDB学习笔记~为IMongoRepository接口添加分页取集合的方法
回到目录 对于数据分页,我们已经见的太多了,几乎每个列表页面都要用到分页,这已经成了一种定理了,在进行大数据展示时,如果不去分页,而直接把数据加载到内存,这简直是不可以去相向的,呵呵,在很多ORM工具 ...
- [MongoDB]Mongo基本使用:
汇总: 1. [MongoDB]安装MongoDB2. [MongoDB]Mongo基本使用:3. [MongoDB]MongoDB的优缺点及与关系型数据库的比较4. [MongoDB]MongoDB ...
- mongo基本操作
创建数据库文件的存放位置,比如d:/mongodb/data/db.启动mongodb服务之前需要必须创建数据库文件的存放文件夹,否则命令不会自动创建,而且不能启动成功. 打开cmd(windows键 ...
随机推荐
- python基础之 装饰器,内置函数
1.闭包回顾 在学习装饰器之前,可以先复习一下什么是闭包? 在嵌套函数内部的函数可以使用外部变量(非全局变量)叫做闭包! def wrapper(): money =10 def inner(num) ...
- C/C++ 获取系统时间 到秒 || 到毫秒
string getNowSysTime(string &outPut) { ] = {}; struct timeval tv; struct timezone tz; struct tm ...
- gRPC 在 Python中的应用
python -m grpc_tools.protoc --proto_path=. --python_out=. --grpc_python_out=. hello.proto 简介 在python ...
- Canvas Demo
<!DOCTYPE html> <html> <head> <title>ゆき</title> </head> <styl ...
- php通过pecl方式安装扩展
安装pecl cd /usr/local/php/bin/ wget http://pear.php.net/go-pear.phar -O go-pear.php php go-pear.php # ...
- Catch That Cow (BFS广搜)
问题描述: Farmer John has been informed of the location of a fugitive cow and wants to catch her immedia ...
- 再谈javascriptjs原型与原型链及继承相关问题
什么是原型语言 只有对象,没有类;对象继承对象,而不是类继承类. “原型对象”是核心概念.原型对象是新对象的模板,它将自身的属性共享给新对象.一个对象不但可以享有自己创建时和运行时定义的属性,而且可以 ...
- redis 列表(list)函数
列表(list)函数 lPush 命令/方法/函数 Description Adds the string value to the head (left) of the list. Creates ...
- 网络-05-端口号-F5-负载均衡设-linux端口详解大全--TCP注册端口号大全备
[root@test1:Standby] config # [root@test1:Standby] config # [root@test1:Standby] config # [root@test ...
- CMOS门电路
参考:https://wenku.baidu.com/view/8582501e964bcf84b9d57bd3.html 1. CMOS与非门(P并N串) 2. CMOS或非门(N并P串 ...