0 运行环境
- MongoDB Community v4.0.5
- mongoimport r4.0.5
- MongoDB shell v4.0.5
- macOS 10.13.5
1 先说背景
在 MongoDB 中的 demo-db 库中有名为 topics 的集合 ,该集合类存储数据类似于论坛的发帖与回复,需要使用 MongoDB shell 进行回复数据的分页查询(按发布时间倒序,每页2条),查询时只返回回复内容,不需要其它字段信息
2 再说干货
2.1 样例数据
{
"title": "文章标题1",
"content": "文章内容1",
"publish_time": {
"$date": "2018-10-01T07:36:11.558Z"
},
"creator": "zhangsan1",
"comments": [
{
"content": "回复内容1",
"publish_time": {
"$date": "2018-10-01T08:36:11.558Z"
},
"creator": "lisi1"
},
{
"content": "回复内容2",
"publish_time": {
"$date": "2018-10-01T09:36:11.558Z"
},
"creator": "lisi2"
},
{
"content": "回复内容3",
"publish_time": {
"$date": "2018-10-01T10:36:11.558Z"
},
"creator": "lisi3"
},
{
"content": "回复内容4",
"publish_time": {
"$date": "2018-10-01T11:36:11.558Z"
},
"creator": "lisi4"
},
{
"content": "回复内容5",
"publish_time": {
"$date": "2018-10-01T12:36:11.558Z"
},
"creator": "lisi5"
}
]
}
2.2 数据导入
数据可以使用 mongoimport 命令进行导入,mongoimport默认在 MongoDB安装目录的 bin 下,建议将MongoDB安装目录的 bin配置在PATH中,方便使用
使用 json 文件导入命令如下:
mongoimport -h localhost:27017 -d demo-db -c topics --file ./topics.json
相关参数说明:
-h 连接的主机或者连接的主机及端口,host:port 格式,默认为本机,端口27017
-d 要导入的数据库 (db)
-c 要导入的集合(collection)
--file 要导入文件的路径
2.3 命令脚本
使用聚合(aggregate)实现相关需求
db.topics.aggregate([
{$match:{"_id":ObjectId("5c517240908400b9bd67261b")}},
{$project:{"comments":1,"_id":0}},
{$unwind:"$comments"},
{$sort:{"comments.publish_time":-1}},
{$skip:0},
{$limit:2}]).pretty();
结果如下:
1)第一页
第一页查询结果.png
2)第二页
第二页查询结果.png
相关说明:mongodb的聚合(aggregate)使用的是管道(pipeline)的模式,上一个阶段的处理的结果做为下一个阶段的输入,下面分别对相关阶段做以解释说明
{$match:{"_id":ObjectId("5c517240908400b9bd67261b")}}
匹配主键为5c517240908400b9bd67261b
的记录,数据导入时未设置主键,该主键默认由 mongodb自动生成,需先查询主文档获得{$project:{"comments":1,"_id":0}}
设置投影,只显示comments
字段{$unwind:"$comments"}
将comments
字段结果集展开{$sort:{"comments.publish_time":-1}}
按发布时间倒序{$skip:0}
分页参数,第一页,第N页取值 (N-1) * 单页条数{$limit:2}
单页条数
4 结束语
以上为使用 MongoDB shell 的实现方式,后一篇准备使用原生 MongoDB 驱动和 spring-data-mongodb 实现分别进行以上内容的实现,敬请期待。
网友评论