Skip to content
Related Articles

Related Articles

Python MongoDB – Sort
  • Last Updated : 14 Aug, 2020

MongoDB is a cross-platform document-oriented database program and the most popular NoSQL database program. The term NoSQL means non-relational. MongoDB stores the data in the form of key-value pairs. It is an Open Source, Document Database which provides high performance and scalability along with data modeling and data management of huge sets of data in an enterprise application. MongoDB also provides the feature of Auto-Scaling. It uses JSON like documents, which makes the database very flexible and scalable.

Note: For more information, refer to MongoDB and Python

Sorting the MongoDB documents

sort() method is used for sorting the database in some order. This method accepts two parameters first is the fieldname and the second one is for the direction to sort. (By default it sorts in ascending order)

Syntax:

sort(fieldname, direction)

Note: 1 as the direction is used for ascending order and -1 as the direction is used for descending order



Example 1: Using sort() function to sort the result alphabetically by name.

Let’s suppose the database looks like this –

python-mongodb-db

filter_none

edit
close

play_arrow

link
brightness_4
code

# python code to sort elements
# alphabetically in ascending order
   
import pymongo
  
  
# establishing connection
# to the database
my_client = pymongo.MongoClient('localhost', 27017)
  
# Name of the databse
mydb = my_client["gfg"]
  
# Name of the collection
mynew = mydb["names"]
   
# sorting function 
mydoc = mynew.find().sort("name")
   
for x in mydoc:
    print(x)

chevron_right


Output :

python-mongodb-sort-1

Example 2: Sorting in descending order

filter_none

edit
close

play_arrow

link
brightness_4
code

import pymongo
  
  
# establishing connection 
# to the database
my_client = pymongo.MongoClient('localhost', 27017)
  
# Name of the databse
mydb = my_client["gfg"]
  
# Name of the collection
mynew = mydb["names"]
   
# sorting function with -1 
# as direction
mydoc = mynew.find().sort("name", -1)
   
for x in mydoc:
    print(x)

chevron_right


Output :

python-mongodb-sort-2

Attention geek! Strengthen your foundations with the Python Programming Foundation Course and learn the basics.

To begin with, your interview preparations Enhance your Data Structures concepts with the Python DS Course.

My Personal Notes arrow_drop_up
Recommended Articles
Page :