簡單的投影
稍微用過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
),當然就會進行投影篩選~