Loading

MongoDB投影有$slice如何只显示该字段

简单的投影

稍微用过MongoDB的都知道,投影很简单,就直接

db.student.find({_id:ObjectId('5a5085aed8f10c1a6cc0395b')},{comments: 1})

添加$slice的投影

然而,当我要给comments分页($slice)如何做呢?

错误的做法

以下给出了错误的做法

db.student.find({_id:ObjectId('5a5085aed8f10c1a6cc0395b')},{comments: 1, comments:{$slice:[0,1]}})

这样写的话,就只有分页,然后字段显示全部

原因
对象中,同名字段,后者会覆盖前者。所以{comments: 1, comments: {$slice:[0,1]}}中实际生效的只有comments:{$slice:[0,1]}
同理,如果两个调换位置变成{comments: {$slice:[0,1]}, comments: 1},那么实际生效的就是 comments: 1没有分页

正确的写法

多写一个随意的字段(不跟已有的字段已有)可以做到,具体原理求告知

db.student.find({_id:ObjectId('5a5085aed8f10c1a6cc0395b')}, {comments:{$slice:[0,1]},  xxx:1})

简单的投影

稍微用过MongoDB的都知道,投影很简单,就直接

db.student.find({_id:ObjectId('5a5085aed8f10c1a6cc0395b')},{comments: 1})

添加$slice的投影

然而,当我要给comments分页($slice)如何做呢?

错误的做法

以下给出了错误的做法

db.student.find({_id:ObjectId('5a5085aed8f10c1a6cc0395b')},{comments: 1, comments:{$slice:[0,1]}})

这样写的话,就只有分页,然后字段显示全部

原因
对象中,同名字段,后者会覆盖前者。所以{comments: 1, comments: {$slice:[0,1]}}中实际生效的只有comments:{$slice:[0,1]}
同理,如果两个调换位置变成{comments: {$slice:[0,1]}, comments: 1},那么实际生效的就是 comments: 1没有分页

正确的写法

多写一个随意的字段(不跟已有的字段已有)可以做到

db.student.find({_id:ObjectId('5a5085aed8f10c1a6cc0395b')}, {comments:{$slice:[0,1]},  xxx:1})

_id怎么样都会显示,随意乱写不好,统一用_id吧

db.student.find({_id:ObjectId('5a5085aed8f10c1a6cc0395b')}, {comments:{$slice:[0,1]},  _id:1})

原理

被slice的字段一定会显示,加上其他的字段(例如_id),当然就会进行投影筛选~

posted @ 2018-01-09 23:26  小新是也  阅读(1389)  评论(1编辑  收藏  举报