$slice is used to slice the data in the array while retrieving , it will limit the number of records to display from the array while retrieving the data.
Passing Positive integer will result the data from the beginning of the array.
Passing Negative integer will result the data from the other end of the array.
Syntax:
db.collection.find({Key:value},{arrayKey:{$slice:CountToDisaplay}})
db.collection.find({Key:value},{arrayKey:{$slice:[skip,limit]}})
Example:
Initial data:
Retrieving first two records from the array
db.studentDetails.find({Name:'Raghav'},{Marks:{$slice:2}})
output:
{"Name" : "Raghav","Department" : "EEE","Languages" : [ { "speak" : "Telugu","read" : "Telugu"} ],"Marks" : [ 98,99 ]}
Retrieving last two records from the array
db.studentDetails.find({Name:'Raghav'},{Marks:{$slice:-2}})
output:
{"Name" : "Raghav","Department" : "EEE","Languages" : [ { "speak" : "Telugu","read" : "Telugu"} ],"Marks" : [86,85 ]}
Retrieving third, fourth and fifth records from the array
db.studentDetails.find({Name:'Raghav'},{Marks:{$slice:[2,3]}})
output:
{"Name" : "Raghav","Department" : "EEE","Languages" : [ { "speak" : "Telugu","read" : "Telugu"} ],"Marks" : [26,78,86 ]}