-
Notifications
You must be signed in to change notification settings - Fork 81
MongoDB Sort Records
Ramesh Fadatare edited this page Jan 12, 2020
·
2 revisions
In this post, we will learn how to sort records in MongoDB.
To sort documents in MongoDB, you need to use the sort() method. The method accepts a document containing a list of fields along with their sorting order. To specify sorting order 1 and -1 are used. 1 is used for ascending order while -1 is used for descending order.
The basic syntax of the sort() method is as follows −
> db.COLLECTION_NAME.find().sort({KEY:1})
Consider the collection "posts" with following documents.
db.posts.insertMany([{
"title" : "MongoDB Overview",
"description" : "MongoDB is no sql database",
"by" : "Java Guides",
"url" : "https://javaguides.net",
"tags" : [
"mongodb",
"database",
"NoSQL"
],
"likes" : 100
},
{
"title" : "NoSQL Database",
"description" : "NoSQL database doesn't have tables",
"by" : "Java Guides",
"url" : "https://javaguides.net",
"tags" : [
"mongodb",
"database",
"NoSQL"
],
"likes" : 20,
"comments" : [
{
"user" : "user1",
"message" : "My first comment",
"dateCreated" : ISODate("2013-12-10T09:35:00Z"),
"like" : 0
}
]
},
{
"title" : "MongoDB CRUD Operations",
"description" : "MongoDB CRUD Operations",
"by" : "Java Guides",
"url" : "https://javaguides.net",
"tags" : [
"mongodb",
"database",
"NoSQL"
],
"likes" : 20,
"comments" : [
{
"user" : "user1",
"message" : "My first comment",
"dateCreated" : ISODate("2013-12-10T09:35:00Z"),
"like" : 0
}
]
}]);
Following example will display the documents sorted by title in the descending order.
> db.posts.find({},{"title":1,_id:0}).sort({"title":-1});
{ "title" : "NoSQL Database" }
{ "title" : "MongoDB Overview" }
{ "title" : "MongoDB CRUD Operations" }
The default is ascending order so If I don’t provide any value in the sort() method then it will sort the records in ascending order as shown below:
> db.posts.find({},{"title":1,_id:0}).sort({});
{ "title" : "MongoDB Overview" }
{ "title" : "NoSQL Database" }
{ "title" : "MongoDB CRUD Operations" }