Example find limit in mongoDB with nodejs

Limit the Result

To limit the result in MongoDB, we use the limit() method.

The limit() method takes one parameter, a number defining how many documents to return.

Example: Limit the result to only return 5 documents

 

var MongoClient = require('mongodb').MongoClient;

var url = "mongodb://192.168.1.122:27017/";

MongoClient.connect(url, function(err, db) {

  if (err) throw err;

  var dbo = db.db("mydb");

  dbo.collection("customers").find().limit(5).toArray(function(err, result) {

    if (err) throw err;

    console.log(result);

    db.close();

  });

});

 

Run and result:

 

C:\Nodejs>node mongodbFindLimitData.js

[ { _id: 5addc65714026d03e08822f3,

    name: 'name1',

    address: 'Highway 71' },

  { _id: 5addc65714026d03e08822f4,

    name: 'name2',

    address: 'Lowstreet 4' },

  { _id: 5addc65714026d03e08822f5,

    name: 'name3',

    address: 'Apple st 652' },

  { _id: 5addc65714026d03e08822f6,

    name: 'name4',

    address: 'Mountain 21' },

  { _id: 5addc65714026d03e08822f7,

    name: 'Mickey',

    address: 'Canyon 123' } ]