Nodejs MongoDB limit

limit() method is used to get the number of documents in MongoDB.
limit() method works along with the find() method.

Suppose, You have users collections that have 4 documents.


[
	{
		"_id" : ObjectId("5fdc8b842649b8748d4ec107"),
		"name" : "John",
		"age" : 35
	},
	{
		"_id" : ObjectId("5fdcdb87b6dad382104b0f86"),
		"name" : "Rom",
		"age" : 31
	},
	{
		"_id" : ObjectId("5fdcdb87b6dad382104b0f87"),
		"name" : "Mathew",
		"age" : 32
	},
	{
		"_id" : ObjectId("5fdcdb87b6dad382104b0f88"),
		"name" : "Sachin",
		"age" : 38
	}
]

Firstly create the get_document.js file.


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

let url="mongodb://localhost:27017/";
var options = {
  useNewUrlParser: true,
  useUnifiedTopology: true,  
}
MongoClient.connect(url,options, function (err, connection_obj) {
  try{
     if (err) throw err;
     var dbo = connection_obj.db("users_management");
     dbo.collection("users").find({}).limit(2).toArray(function(err, res) {
      if (err) throw err;
       console.log("documents show successfully");
       console.log("result:",res);
       connection_obj.close();
    });

  }catch(err){

    console.log("connection fails");
  
  }

Now, run the get_document.js file.


node get_document.js
Output:-
documents show successfully
result: [ { _id: 5fddc8f7329e1da50a4ec725, name: ‘John’, age: 35 },
{ _id: 5fddc8f7329e1da50a4ec726, name: ‘Rom’, age: 31 } ]