Example find limit in mongodb with nodejs use mongoose

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 mongoose = require('mongoose');

var db = mongoose.connection;

var Schema = mongoose.Schema;

db.on('error', console.error);

db.once('open', function () {

    console.log("db connect");

    var customers = new Schema({

        name: {type: String, required: true},

        address: {type: String, required: true}

    });

    var customerObject = db.model('customers', customers);

    customerObject.find({}, function(err, result){

        if(err){

            console.log("error query");

        }else{

            console.log(result);

        }

    }).limit(5);

});

mongoose.connect('mongodb://192.168.1.122:27017/codewr');

 

Run and result:

 

C:\Nodejs>node mongooseFindLimitData.js

db connect

[ { _id: 5adf13268d58740ac846a6e9,

    name: 'name2',

    address: 'Lowstreet 4',

    __v: 0 },

  { _id: 5adf13268d58740ac846a6ea,

    name: 'name3',

    address: 'Apple st 652',

    __v: 0 },

  { _id: 5adf13268d58740ac846a6eb,

    name: 'name4',

    address: 'Mountain 21',

    __v: 0 },

  { _id: 5adf13268d58740ac846a6ec,

    name: 'name5',

    address: 'Valley 345',

    __v: 0 },

  { _id: 5adf13268d58740ac846a6ed,

    name: 'name6',

    address: 'Ocean blvd 2',

    __v: 0 } ]