To sort in MongoDB, use sort(). For displaying only a specific number of values, use LIMIT. Let us create a collection with documents −
> db.demo254.insertOne({"Name":"Chris"});
{
"acknowledged" : true,
"insertedId" : ObjectId("5e47a0ab1627c0c63e7dba7f")
}
> db.demo254.insertOne({"Name":"Adam"});
{
"acknowledged" : true,
"insertedId" : ObjectId("5e47a0b01627c0c63e7dba80")
}
> db.demo254.insertOne({"Name":"Bob"});
{
"acknowledged" : true,
"insertedId" : ObjectId("5e47a0b71627c0c63e7dba81")
}Display all documents from a collection with the help of find() method −
> db.demo254.find();
This will produce the following output −
{ "_id" : ObjectId("5e47a0ab1627c0c63e7dba7f"), "Name" : "Chris" }
{ "_id" : ObjectId("5e47a0b01627c0c63e7dba80"), "Name" : "Adam" }
{ "_id" : ObjectId("5e47a0b71627c0c63e7dba81"), "Name" : "Bob" }Following is the query to sort −
> db.demo254.find().sort({"Name":1});This will produce the following output −
{ "_id" : ObjectId("5e47a0b01627c0c63e7dba80"), "Name" : "Adam" }
{ "_id" : ObjectId("5e47a0b71627c0c63e7dba81"), "Name" : "Bob" }
{ "_id" : ObjectId("5e47a0ab1627c0c63e7dba7f"), "Name" : "Chris" }Following is the query to sort and display only a specific number of records with limit().
> db.demo254.find().sort({"Name":1}).limit(2);This will produce the following output −
{ "_id" : ObjectId("5e47a0b01627c0c63e7dba80"), "Name" : "Adam" }
{ "_id" : ObjectId("5e47a0b71627c0c63e7dba81"), "Name" : "Bob" }