Search code examples
node.jsmongodbmonk

NodeJS/MongoDB: Perform Slice operation on an array field


I am having a tough time trying to execute a slice on an array I have a collection called comments, each document has an array field, i want to access it and apply slice for paging purpose please help !! tried monk and mongodb no good

Example:

 {  
   _id:xyz,
   msgs:[{.....},{.....},{.....}]
 }


database.collection("comments")
  .find({"_id": id},{ "msgs": { "$slice": [2,5] } })
  .toArray( function(err, result){
        //implementation
   });

Solution

  • For mongodb Driver:

    Instead of

    .find({"_id": id},{ "msgs": { "$slice": [2,5] } })
    

    Use

    .find({"_id": id}).project({ "msgs": { "$slice": [2,5] } })
    

    As given here the $slice operator is of Projection type. The mongodb driver for NodeJS needs call to an extra .project function to project selective fields as well as to use projection operators.