limit() method

In MongoDB, limit() method is used to get the limit of documents from the collection. this method has only one parameter which should be numeric only.

Syntax:-

 db.collectionName.find().limit(number);

Consider, you have employees collection

[
	{
		"_id" : ObjectId("5f26e736deec6e20ea057831"),
		"name" : "John",
		"age" : 35,
		"department" : "department A",
		"salary" : 200000
	},
	{
		"_id" : ObjectId("5f26e7c0deec6e20ea057832"),
		"name" : "Rom",
		"age" : 30,
		"department" : "department A",
		"salary" : 70000
	},
	{
		"_id" : ObjectId("5f26e9dedeec6e20ea057833"),
		"name" : "Tony",
		"age" : 31,
		"department" : "department B",
		"salary" : 40000
	},
	{
		"_id" : ObjectId("5f26e9dedeec6e20ea057834"),
		"name" : "Peter",
		"age" : 32,
		"department" : "department B",
		"salary" : 30000
	},
	{
		"_id" : ObjectId("5f26e9dedeec6e20ea057835"),
		"name" : "Andrew",
		"age" : 33,
		"department" : "department C",
		"salary" : 20000
	}
]

Now, if you want to get only two documents then you have to use limit() method.

> db.employees.find().limit(2).toArray();

Output:-

[
	{
		"_id" : ObjectId("5f26e736deec6e20ea057831"),
		"name" : "John",
		"age" : 35,
		"department" : "department A",
		"salary" : 200000
	},
	{
		"_id" : ObjectId("5f26e7c0deec6e20ea057832"),
		"name" : "Rom",
		"age" : 30,
		"department" : "department A",
		"salary" : 70000
	}
]