node.jsnode-mongodb-nativemonk

Limit find using Monk in mongoDB


I have a large collection of documents. I want to get the first 100 of these. From the Monk Docs, this is the find method I am using

var documents = [];
users.find({}, function (err, docs){
  for(i=0;i<100;i++)
     documents.push(docs[i]);
});

This is highly wasteful since, the entire documents are anyway retrieved. I want something like this (from the mongodb docs)

docs =  db.users.find().limit( 100 );

I tried in monk,

users.find({}, function (err, docs){
  for(i=0;i<docs.length;i++)
     documents.push(docs[i]);
}).limit(100);

But it gives an error saying that there is no function limit in the "promise" object that is returned before it.

Is there such an option in Monk to limit the number of documents?


Solution

  • Yes, you can pass it as an option in the second parameter:

    users.find({}, { limit : 100 }, function (err, docs){
      for(i=0;i<docs.length;i++)
         documents.push(docs[i]);
    });
    

    This comes from the native node mongodb driver, which monk wraps via mongoskin:

    http://mongodb.github.io/node-mongodb-native/markdown-docs/queries.html#query-options