In this part of the Learn Mongo Series, we will learn how to sort records in a collection in mongodb. We will be sorting records in ascending as well as descending order.
In mongodb we can sort the records using the sort
command.
The syntax for sort command is given below : db.COLLECTION_NAME.find().sort()
. We can sort the records in ascending or descending order.
Let's understand them one by one.
key
parameter with the sort method. If the value passed witin the key
is 1
, then the record is sorted in ascending order. Although the default order is also ascending order so if nothing is passed as key,
then also collection is sorted in ascending order. An example is given below.
> db.details.find().pretty()
{
"_id" : ObjectId("5996be4fa4b26dc0d6d75c1d"),
"age" : "11",
"description" : "learn mongodb",
"name" : "Updated a"
}
{
"_id" : ObjectId("5996be4fa4b26dc0d6d75c1c"),
"name" : "nodejsera",
"age" : "10",
"description" : "Mongodb tuttorial series"
}
{
"_id" : ObjectId("5996f7c3a4b26dc0d6d75c1f"),
"name" : "b",
"age" : "20",
"description" : "this is B"
}
age
field :
> db.details.find().sort("age" : 1}).pretty()
{
"_id" : ObjectId("5996be4fa4b26dc0d6d75c1c"),
"name" : "nodejsera",
"age" : "10",
"description" : "Mongodb tuttorial series"
}
{
"_id" : ObjectId("5996be4fa4b26dc0d6d75c1d"),
"age" : "11",
"description" : "learn mongodb",
"name" : "Updated a"
}
{
"_id" : ObjectId("5996f7c3a4b26dc0d6d75c1f"),
"name" : "b",
"age" : "20",
"description" : "this is B"
}
key
parameter with the sort method. If the value passed witin the key
is -1
, then the record is sorted in descending order. An example is given below.
> db.details.find().sort({"name" : -1}).pretty()
{
"_id" : ObjectId("5996be4fa4b26dc0d6d75c1d"),
"name" : "Up",
"age" : "11",
"description" : "learn mongodb"
}
{
"_id" : ObjectId("5996be4fa4b26dc0d6d75c1c"),
"name" : "nodejsera",
"age" : "10",
"description" : "Mongodb tutorial series"
}
{
"_id" : ObjectId("5996f7c3a4b26dc0d6d75c1f"),
"name" : "b",
"age" : "20",
"description" : "this is B"
}
>
In this part of learn mongo series , we learned about how we can sort a collection in mongodb in ascending and descending order. We learned the following commands of mongodb :
.pretty() :
This method is used to display the data in presentable form. .sort({"key"})
This command is used to sort the collection in ascending order. .sort({"key" : 1})
Again this command is used to sort the collection in ascending order. .sort({"key" : -1})
This command is used to sort the collection in descending order.