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);
Suppose, you have employees collection which has 3 documents.
[
{
“_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(“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
}
]
Now, if you want to get only one documents then you have to use the limit() method.
> db.employees.find().limit(1).toArray();
Output:-
[
{
“_id” : ObjectId(“5f26e736deec6e20ea057831”),
“name” : “John”,
“age” : 35,
“department” : “department A”,
“salary” : 200000
}
]
{
“_id” : ObjectId(“5f26e736deec6e20ea057831”),
“name” : “John”,
“age” : 35,
“department” : “department A”,
“salary” : 200000
}
]