MongoDB sort by field (with Examples)

In this MongoDB tutorial, We are going to learn “How can we sort the field of MongoDB“. And we will also discuss how many different ways we can sort the value in MongoDB. These are the following topics that we are going to cover in this tutorial:

  • MongoDB sort by field
  • MongoDB sort by field name
  • MongoDB sort by field value
  • MongoDB sort by field ascending order
  • MongoDB sort by field descending order
  • MongoDB sort by multiple fields
  • MongoDb sort by field with limit
  • MongoDB sort by field in python
  • MongoDB sort by field length
  • MongoDB sort by field array

MongoDB sort by field

In MongoDB, for sorting the document by the field you have to use the sort() method. This method contains a list of fields. By using field names we can specify sorting in ascending and descending order by using 1 and -1 respectively.

Syntax:

>db.collection_name.find().sort()

Example:

In this example, we are going to Insert some documents into the collection.

>db.test.find()
{_id : ObjectId("507f191e810c19729de860e1"), title: "MySQL"}
{_id : ObjectId("507f191e810c19729de860e2"), title: "SQL"}
{_id : ObjectId("507f191e810c19729de860e3"), title: "MongoDB"}
{_id : ObjectId("507f191e810c19729de860e4"), title: "DynamoDB"}
{_id : ObjectId("507f191e810c19729de860e5"), title: "PostgreSQL"}

these are some of the documents that we inserted into the test collection.

>db.test.find().sort({"title")
{_id : ObjectId("507f191e810c19729de860e4"), title: "DynamoDB"}
{_id : ObjectId("507f191e810c19729de860e3"), title: "MongoDB"}
{_id : ObjectId("507f191e810c19729de860e1"), title: "MySQL"}
{_id : ObjectId("507f191e810c19729de860e5"), title: "PostgreSQL"}
{_id : ObjectId("507f191e810c19729de860e2"), title: "SQL"}

Note that, if you don’t specify anything in the sort() method it will display all the documents in ascending order.

Read: Pros and cons of MongoDB

MongoDB sort by field name

In MongoDB, For sort by field name, we use the sort() method and in the method specify the variables field name and direction(ascending or descending order).

sort("field_name":1)    #For ascending order
sort("field_name":-1)   #For descending order

Syntax:

>db.collection_name.find().sort({"Key":1})

Example:

> db.product.insert({ "_id" : 1, "item" : { "name" : "HighLander", "type" : "toyota" }, "price" : 2.8 })
WriteResult({ "nInserted" : 1 })
> db.product.insert({ "_id" : 2, "item" : { "name" : "Swift", "type" : "suzuki" }, "price" : 3.9 })
WriteResult({ "nInserted" : 1 })
> db.product.insert({ "_id" : 3, "item" : { "name" : "Mirage G4", "type" : "mitsubishi" }, "price" : 3.2 })
WriteResult({ "nInserted" : 1 })
> db.product.insert({ "_id" : 4, "item" : { "name" : "Altima", "type" : "Nissan" }, "price" : 2.4 })
WriteResult({ "nInserted" : 1 })
> db.product.insert({ "_id" : 5, "item" : { "name" : "Veloster", "type" : "Hyundai" }, "price" : 4.5 })
WriteResult({ "nInserted" : 1 })

As you can see I have inserted 5 documents into the product collection. Now to check all the documents are inserted or not into collection use the find() method.

> db.product.find()
{ "_id" : 1, "item" : { "name" : "HighLander", "type" : "toyota" }, "price" : 2.8 }
{ "_id" : 2, "item" : { "name" : "Swift", "type" : "suzuki" }, "price" : 3.9 }
{ "_id" : 3, "item" : { "name" : "Mirage G4", "type" : "mitsubishi" }, "price" : 3.2 }
{ "_id" : 4, "item" : { "name" : "Altima", "type" : "Nissan" }, "price" : 2.4 }
{ "_id" : 5, "item" : { "name" : "Veloster", "type" : "Hyundai" }, "price" : 4.5 }

We successfully inserted the documents into the collection. Now you can sort them by using the sort() method and specify any field name into the method according to what you want to sort.

> db.product.find().sort( {"item" : 1} )
{ "_id" : 1, "item" : { "name" : "HighLander", "type" : "toyota" }, "price" : 2.8 }
{ "_id" : 2, "item" : { "name" : "Swift", "type" : "suzuki" }, "price" : 3.9 }
{ "_id" : 3, "item" : { "name" : "Mirage G4", "type" : "mitsubishi" }, "price" : 3.2 }
{ "_id" : 4, "item" : { "name" : "Altima", "type" : "Nissan" }, "price" : 2.4 }
{ "_id" : 5, "item" : { "name" : "Veloster", "type" : "Hyundai" }, "price" : 4.5 }

Here, you can see we successfully sorted the documents using field value item and then specify 1 for ascending order, You can also sort it into descending order as well by using -1.

Read: Create tables in MongoDB

MongoDB sort by field value

For sorting the document by field value, you have to use the sort() method and here you have to specify the field name and direction either use 1 or -1 for ascending and descending order respectively.

Syntax:

>db.collection_name.find().sort({"Key":1})

Example:

> db.product.insert({ "_id" : 1, "item" : { "name" : "HighLander", "type" : "toyota" }, "price" : 2.8 })
WriteResult({ "nInserted" : 1 })
> db.product.insert({ "_id" : 2, "item" : { "name" : "Swift", "type" : "suzuki" }, "price" : 3.9 })
WriteResult({ "nInserted" : 1 })
> db.product.insert({ "_id" : 3, "item" : { "name" : "Mirage G4", "type" : "mitsubishi" }, "price" : 3.2 })
WriteResult({ "nInserted" : 1 })
> db.product.insert({ "_id" : 4, "item" : { "name" : "Altima", "type" : "Nissan" }, "price" : 2.4 })
WriteResult({ "nInserted" : 1 })
> db.product.insert({ "_id" : 5, "item" : { "name" : "Veloster", "type" : "Hyundai" }, "price" : 4.5 })
WriteResult({ "nInserted" : 1 })

As you can see I have inserted 5 documents into the product collection. You can also check it by using the find() method.

> db.product.find()
{ "_id" : 1, "item" : { "name" : "HighLander", "type" : "toyota" }, "price" : 2.8 }
{ "_id" : 2, "item" : { "name" : "Swift", "type" : "suzuki" }, "price" : 3.9 }
{ "_id" : 3, "item" : { "name" : "Mirage G4", "type" : "mitsubishi" }, "price" : 3.2 }
{ "_id" : 4, "item" : { "name" : "Altima", "type" : "Nissan" }, "price" : 2.4 }
{ "_id" : 5, "item" : { "name" : "Veloster", "type" : "Hyundai" }, "price" : 4.5 }

We successfully inserted the documents into the collection. Now we can sort them by using the sort() method and specify any field into the method and sort it easily as your requirement.

> db.product.find().sort( {"_id" : -1} )
{ "_id" : 5, "item" : { "name" : "Veloster", "type" : "Hyundai" }, "price" : 4.5 }
{ "_id" : 4, "item" : { "name" : "Altima", "type" : "Nissan" }, "price" : 2.4 }
{ "_id" : 3, "item" : { "name" : "Mirage G4", "type" : "mitsubishi" }, "price" : 3.2 }
{ "_id" : 2, "item" : { "name" : "Swift", "type" : "suzuki" }, "price" : 3.9 }
{ "_id" : 1, "item" : { "name" : "HighLander", "type" : "toyota" }, "price" : 2.8 }

Here, you can see we successfully sorted the documents using field value _id and then specify -1 for descending order.

Read: How does MongoDB create a collection

MongoDB sort by field ascending order

For ascending order, you have to specify 1 next to the field name which you want to sort in ascending order.

Syntax:

db.collection_name.find().sort({name:1})

Example:

> db.data.find()
{ "_id" : ObjectId("6119f45f663e8943eb886c1a"), "First_Name" : "Harry", "Last_Name" : "Potter", "Age" : 24 }
{ "_id" : ObjectId("6119f484663e8943eb886c1b"), "First_Name" : "Steve", "Last_Name" : "Morse", "Age" : 21 }
{ "_id" : ObjectId("6119f4ad663e8943eb886c1c"), "First_Name" : "Roger", "Last_Name" : "Paice", "Age" : 26 }
{ "_id" : ObjectId("6119f4c5663e8943eb886c1d"), "First_Name" : "Kim", "Last_Name" : "Janner", "Age" : 29 }

After inserting the documents into the collection use the sort() method and specify field name with 1 for ascending order.

> db.data.find().sort({"First_Name":1})
{ "_id" : ObjectId("6119f45f663e8943eb886c1a"), "First_Name" : "Harry", "Last_Name" : "Potter", "Age" : 24 }
{ "_id" : ObjectId("6119f4c5663e8943eb886c1d"), "First_Name" : "Kim", "Last_Name" : "Janner", "Age" : 29 }
{ "_id" : ObjectId("6119f4ad663e8943eb886c1c"), "First_Name" : "Roger", "Last_Name" : "Paice", "Age" : 26 }
{ "_id" : ObjectId("6119f484663e8943eb886c1b"), "First_Name" : "Steve", "Last_Name" : "Morse", "Age" : 21 }

you can see we use the field First_Name and then specify 1 for ascending order and we sorted the documents easily.

Read: MongoDB backup and restore

MongoDB sort by field descending order

For descending order, you have to specify -1 next to the field name which you want to sort in descending order.

Syntax:

db.collection_name.find().sort({name:-1})

Example:

> db.data.find()
{ "_id" : ObjectId("6119f45f663e8943eb886c1a"), "First_Name" : "Harry", "Last_Name" : "Potter", "Age" : 24 }
{ "_id" : ObjectId("6119f484663e8943eb886c1b"), "First_Name" : "Steve", "Last_Name" : "Morse", "Age" : 21 }
{ "_id" : ObjectId("6119f4ad663e8943eb886c1c"), "First_Name" : "Roger", "Last_Name" : "Paice", "Age" : 26 }
{ "_id" : ObjectId("6119f4c5663e8943eb886c1d"), "First_Name" : "Kim", "Last_Name" : "Janner", "Age" : 29 }

After inserting the documents into the collection use the sort() method and specify field name with -1 for descending order.

> db.data.find().sort({"Age":-1})
{ "_id" : ObjectId("6119f4c5663e8943eb886c1d"), "First_Name" : "Kim", "Last_Name" : "Janner", "Age" : 29 }
{ "_id" : ObjectId("6119f4ad663e8943eb886c1c"), "First_Name" : "Roger", "Last_Name" : "Paice", "Age" : 26 }
{ "_id" : ObjectId("6119f45f663e8943eb886c1a"), "First_Name" : "Harry", "Last_Name" : "Potter", "Age" : 24 }
{ "_id" : ObjectId("6119f484663e8943eb886c1b"), "First_Name" : "Steve", "Last_Name" : "Morse", "Age" : 21 }

you can see we use the field Age and then specify -1 for descending order and we sorted the documents easily.

Read: How to create a new database in MongoDB

MongoDB sort by multiple fields

In MongoDB, we can also sort the multiple fields as well. For sorting multiple fields you only need to separate each field by a comma. The documents will be sorted in this sequence first field, a second field and so on.

Syntax:

db.test.find().sort({field_1 : 1, field_2 : -1})

Example:

> db.data.find()
{ "_id" : ObjectId("6119f45f663e8943eb886c1a"), "First_Name" : "Harry", "Last_Name" : "Potter", "Age" : 24 }
{ "_id" : ObjectId("6119f484663e8943eb886c1b"), "First_Name" : "Steve", "Last_Name" : "Morse", "Age" : 21 }
{ "_id" : ObjectId("6119f4ad663e8943eb886c1c"), "First_Name" : "Roger", "Last_Name" : "Paice", "Age" : 26 }
{ "_id" : ObjectId("6119f4c5663e8943eb886c1d"), "First_Name" : "Kim", "Last_Name" : "Janner", "Age" : 29 }

Here, you see we inserted some documents into the data collection. For retrieving the data with sort by multiple fields values then you have to do this as

> db.data.find().sort({"First_Name":1, "Last_Name":-1})
{ "_id" : ObjectId("6119f45f663e8943eb886c1a"), "First_Name" : "Harry", "Last_Name" : "Potter", "Age" : 24 }
{ "_id" : ObjectId("6119f4c5663e8943eb886c1d"), "First_Name" : "Kim", "Last_Name" : "Janner", "Age" : 29 }
{ "_id" : ObjectId("6119f4ad663e8943eb886c1c"), "First_Name" : "Roger", "Last_Name" : "Paice", "Age" : 26 }
{ "_id" : ObjectId("6119f484663e8943eb886c1b"), "First_Name" : "Steve", "Last_Name" : "Morse", "Age" : 21 }

In this example, We took two fields First_Name, Last_Name and specify 1, -1 respectively for ascending and descending order. We can also take more fields as well as per the requirement.

Read: How to install MongoDB

MongoDB sort by field with limit

In MongoDB, If you want to display only a limited result set then you can do this by using the limit() method and specifying the number of documents(in a number) that you want to display.

Syntax:

db.collection_name.find().limit(number).sort({field_1:1})

Example:

> db.data.find()
{ "_id" : ObjectId("6119f45f663e8943eb886c1a"), "First_Name" : "Harry", "Last_Name" : "Potter", "Age" : 24 }
{ "_id" : ObjectId("6119f484663e8943eb886c1b"), "First_Name" : "Steve", "Last_Name" : "Morse", "Age" : 21 }
{ "_id" : ObjectId("6119f4ad663e8943eb886c1c"), "First_Name" : "Roger", "Last_Name" : "Paice", "Age" : 26 }
{ "_id" : ObjectId("6119f4c5663e8943eb886c1d"), "First_Name" : "Kim", "Last_Name" : "Janner", "Age" : 29 }

Here, you can see we inserted some documents into data collection.

Now, we are going to retrieve the limited number of data with the limit() method

> db.data.find().limit(3).sort({"First_Name":1, "Last_Name":-1})
{ "_id" : ObjectId("6119f45f663e8943eb886c1a"), "First_Name" : "Harry", "Last_Name" : "Potter", "Age" : 24 }
{ "_id" : ObjectId("6119f4c5663e8943eb886c1d"), "First_Name" : "Kim", "Last_Name" : "Janner", "Age" : 29 }
{ "_id" : ObjectId("6119f4ad663e8943eb886c1c"), "First_Name" : "Roger", "Last_Name" : "Paice", "Age" : 26 }

Here, we specify 3 in the limit() method, so It will only return the first 3 documents of the collection with all sort by conditions.

Read: MongoDB shutting down with code 100

MongoDB sort by field in python

In MongoDB, For sorting the fields in python we use the same sort() method and we define the parameter, field name and direction(ascending or descending order).

Note that if you only specify the field name and don’t specify the direction then it will automatically display the fields in ascending order.

sort("field_name":1)    #For ascending order
sort("field_name":-1)   #For descending order

Example:

import pymongo

myclient = pymongo.MongoClient("mongodb://127.0.0.1:27017")
mydb = myclient["test"]
mycol = mydb["data"]

mydoc = mycol.find().sort("First_Name":1)

for x in mydoc:
  print(x)

In this example, you need to import the pymongo library for making the connection between MongoDB and python. After that, the class MongoClient enable you to make the connection with the MongoDB server. By default, MongoDB is run on 27017 port.

Here test and data are database and collection respectively, you store it into variable mydb and mycol. You can use any name for the variable. We again declare a variable mydoc and define sort() method condition after that with the help of for loop print the values.

Note that, If you don’t have the pymongo library in your system then first you need to install it. Just go to the command prompt and write this command “pip install pymongo” and it will easily install.

{'_id': ObjectId('6119f45f663e8943eb886c1a'), 'First_Name': 'Harry', 'Last_Name': 'Potter', 'Age': 24.0}
{'_id': ObjectId('6119f4c5663e8943eb886c1d'), 'First_Name': 'Kim', 'Last_Name': 'Janner', 'Age': 29.0}
{'_id': ObjectId('6119f4ad663e8943eb886c1c'), 'First_Name': 'Roger', 'Last_Name': 'Paice', 'Age': 26.0}
{'_id': ObjectId('6119f484663e8943eb886c1b'), 'First_Name': 'Steve', 'Last_Name': 'Morse', 'Age': 21.0}

Read MongoDB shutting down with code 48

MongoDB sort by field length

In MongoDB, We can sort the documents in sort by field length. For sorting this you have to use aggregation operation and after that use sort() method you can sort the fields by length.

What is an aggregate operation?

Aggregation operations group values from multiple documents together and we can perform several operations on the group data return a single result.

Syntax:

db.collection.aggregate(
    [
        {$project: {
            "field": 1,
            "field_length": { $strLenCP: "$field" }
        }},
        {$sort: {"field_length": -1}},
        {$project: {"field_length": 0}}
    ]
)

In the aggregate operation, if you want to work with a subset of fields then you have to use $project otherwise for whole documents you have to use $addFields.

The field must refer to extend field in the documents and the field_length key is customizable because it is calculated on demand.

The $strLenCP operator is used to count the number of code points in the specified string.

Example:

ExampleResults
{ $strLenCP: “MongoDB” }7
{ $strLenCP: “Hello World” } 11

Note that, if the argument resolves to a null value or indicate to missing field the $strLenCP return an error.

Example:

>db.students.aggregate(
    [
        {$project: {
            "fname": 1,
            "field_length": { $strLenCP: "$fname" }
        }},
        {$sort: {"field_length": -1}},
        {$project: {"field_length": 0}}
    ]
)
{ "_id" : ObjectId("611a99340a3322fc1bd8c38c"), "fname" : "Harry" }
{ "_id" : ObjectId("611a99510a3322fc1bd8c38d"), "fname" : "Mikky" }
{ "_id" : ObjectId("611a99100a3322fc1bd8c38b"), "fname" : "Tom" }

In this example, we use the field fname, sort by length and use of -1 is to print documents in descending order.

Read: How to backup PostgreSQL database

MongoDB sort by field array

In MongoDB, We can sort the field array by using the sort() method. In the sort() method you have to specify the field name and direction (ascending or descending order).

Syntax:

db.collection_name.find().sort({"field_name":1})

Example:

First, we insert some documents into the collection

> db.students.insertOne({ "fname":"Tom", "city":"USA", "courses": ["c#", "asp", "node" ]})
{
        "acknowledged" : true,
        "insertedId" : ObjectId("611a99100a3322fc1bd8c38b")
}
> db.students.insertOne({ "fname":"Harry", "city":"Canada", "courses": ["python", "asp", "node" ]})
{
        "acknowledged" : true,
        "insertedId" : ObjectId("611a99340a3322fc1bd8c38c")
}
> db.students.insertOne({ "fname":"Mikky", "city":"New Zealand", "courses": ["python", "asp", "c++" ]})
{
        "acknowledged" : true,
        "insertedId" : ObjectId("611a99510a3322fc1bd8c38d")
}

Here, we inserted these 3 documents into students collection one by one by using the insertOne() method. You can also insert all this together by using the insertMany() method.

> db.students.find().sort({city:-1}).pretty()
{
        "_id" : ObjectId("611a99100a3322fc1bd8c38b"),
        "fname" : "Tom",
        "city" : "USA",
        "courses" : [
                "c#",
                "asp",
                "node"
        ]
}
{
        "_id" : ObjectId("611a99340a3322fc1bd8c38c"),
        "fname" : "Harry",
        "city" : "Canada",
        "courses" : [
                "python",
                "asp",
                "node"
        ]
}
{
        "_id" : ObjectId("611a99510a3322fc1bd8c38d"),
        "fname" : "Mikky",
        "city" : "New Zealand",
        "courses" : [
                "python",
                "asp",
                "c++"
        ]
}

All the documents were inserted into students collections. you can also check it by using the find() method.

Here in this example, we sort the city in descending order by specifying -1 in the sort() method. We also use the pretty() method, which is used to display the result in an easy-to-read format.

Also Read: MongoDB sort by date

In this tutorial, we have learned “MongoDB sort by field” using different approaches with examples. These are some of the topics that we covered in this tutorial

  • MongoDB sort by field
  • MongoDB sort by field value
  • MongoDB sort by field name
  • MongoDB sort by field ascending order
  • MongoDB sort by field decending order
  • MongoDB sort by multiple fields
  • MongoDB sort by field with limit
  • MongoDB sort by field in python
  • MongoDB sort by field length
  • MongoDB sort by field array