Mongodb 分页写法

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/liangxw1/article/details/81942203

Mongodb语句的查询语法和传统的关系型数据库基本不同,Mongodb里关于取数据的分页有几种不同的写法,不同的写法适用不同的场合,

简单的有 limit,skip等,

如果需要取分页数据,同时需要返回总数据条数,并且用一个查询语句,可以用push, slice的语法

{ $slice: [ <array>, <position>, <n> ] }
		{ $group: { _id: null, total: { $sum: 1 }, data: { $push: '$tmp' } } },
		{ $project: { total: '$total', data: { $slice: ['$data', start, length] } } }
db.collection('collection_namea')
    .aggregate(
	[
	    {
			$match: {
				...
			}
		},
		...
		{
			$project: {
				tmp: {
					userid: '$userid',
					username: '$username',
					class: '$class',
					grade: '$grade'
				}
			}
		},
		{ $group: { _id: null, total: { $sum: 1 }, data: { $push: '$tmp' } } },
		{ $project: { total: '$total', data: { $slice: ['$data', start, length] } } }
	]
	)
	.toArray()
	.then((dataset) => {
		...
	})
	.catch((err) => {
		...
	});

猜你喜欢

转载自blog.csdn.net/liangxw1/article/details/81942203