Search code examples
node.jsmongodbmonk

How to use MongoDB $slice in Node.js


I am using monk in my Node.js app to communicate with MongoDB. is there a way to use the $slice modifier with the monk driver.

The query I want to run is

db.messages.find(
   {"_id" : ObjectId("557c46191e7aef1b02d5db73")},
   { msgs: { $slice: -2 }  }
);

Solution

  • Monk does not support "projection" or additional argument objects in it's method signature to .find(). In order to use the "truly native" features there is a .col accessor which allows you to use the native driver collection object:

    var db = require('monk')('localhost/test');
    var messages = db.get('messages');
    
    
    messages.col.find({}, { "msgs": { "$slice": -2 } }).toArray(
      function(err,docs) {
        if (err) throw err;
        console.log( JSON.stringify( docs, undefined, 2 ) );
      }
    );
    

    Also note that since this is the native driver you need to call such things as .toArray() or other method to deal with the Cursor object that is returned. The .toArray() element is analogous to what Monk operations do by default.