Sorting and setting limit in MongoDB using Python

Hello programmer, today we are going to take a look at sorting the collection in ascending and descending order. We will also take a look at the limit method in MongoDB.

Until now we have covered some of the methods in MongoDB which are listed below. I would recommend you to check them out first.

  1. How to create a database in MongoDB in Python
  2. How to insert data into a collection
  3. How to select data from the collection
  4. How to update data from the collection
  5. How to delete and drop data from collection

I know you guys might be confused about what is limit, what does it do, why is it required, and whatnot. All of your questions will be answered as we move further in this tutorial. So stick together and learn all the new stuff with me.

So let’s get started with the easier stuff first which is sorting the collection.

The collection in my database is as shown below. I will be sorting the documents on that database.

{'_id': ObjectId('5dee3c828d178a953eec2ad7'),
'age': 21,
'author': 'Shailesh Bhimanpelli',
'course': 'MongoDB using Python',
'rating': 1}
{'_id': ObjectId('5dee451be59a39bf5e67a6fa'),
'age': 23,
'author': 'Ben Thomas',
'course': 'HTML, CSS',
'rating': 4}
{'_id': ObjectId('5def3b1b2a61b9be930647ff'),
'age': 30,
'author': 'Sorabh Pant',
'course': 'Java',
'rating': 4}
{'_id': ObjectId('5def3b1b2a61b9be93064800'),
'age': 27,
'author': 'Sahil Shah',
'course': 'jQuery',
'rating': 4}
{'_id': ObjectId('5def9b07bd101103e4fcb866'),
'age': 24,
'author': 'Tanmay Tamore',
'course': 'Ethical Hacking',
'rating': 3}
{'_id': ObjectId('5def9b83bd101103e4fcb868'),
'age': 26,
'author': 'Sagar Bhatt',
'course': 'Python',
'rating': 2}

For sorting the collections we use sort() method.

The sort() method takes two arguments. One will be the argument for fieldname and the other one will be for the direction that is to decide whether sorting should be ascending or descending order.

Sorting in ascending order

for i in courses.find().sort('age'):
    print(i)

Output

{'_id': ObjectId('5dee3c828d178a953eec2ad7'),
 'age': 21,
 'author': 'Shailesh Bhimanpelli',
 'course': 'MongoDB using Python',
 'rating': 1}
{'_id': ObjectId('5dee451be59a39bf5e67a6fa'),
 'age': 23,
 'author': 'Ben Thomas',
 'course': 'HTML, CSS',
 'rating': 4}
{'_id': ObjectId('5def9b07bd101103e4fcb866'),
 'age': 24,
 'author': 'Tanmay Tamore',
 'course': 'Ethical Hacking',
 'rating': 3}
{'_id': ObjectId('5def9b83bd101103e4fcb868'),
 'age': 26,
 'author': 'Sagar Bhatt',
 'course': 'Python',
 'rating': 2}
{'_id': ObjectId('5def3b1b2a61b9be93064800'),
 'age': 27,
 'author': 'Sahil Shah',
 'course': 'jQuery',
 'rating': 4}
{'_id': ObjectId('5def3b1b2a61b9be930647ff'),
 'age': 30,
 'author': 'Sorabh Pant',
 'course': 'Java',
 'rating': 4}

Here as we did not mention the direction so MongoDB sorted the collection in ascending order. Sorting in MongoDB is by default done in ascending order. But if you wish to specify the direction then run the following code. This code will also produce the same output.

for i in courses.find().sort('age', 1):
    print(i)

Here we specify the direction as which indicates the MongoDB to sort the collection in ascending order.

Sorting in descending order

To sort the collection in descending order the only change that we have to do is to take the direction argument as -1.

for i in courses.find().sort('age', -1): 
    print(i)

Output

{'_id': ObjectId('5def3b1b2a61b9be930647ff'),
'age': 30,
'author': 'Sorabh Pant',
'course': 'Java',
'rating': 4}
{'_id': ObjectId('5def3b1b2a61b9be93064800'),
'age': 27,
'author': 'Sahil Shah',
'course': 'jQuery',
'rating': 4}
{'_id': ObjectId('5def9b83bd101103e4fcb868'),
'age': 26,
'author': 'Sagar Bhatt',
'course': 'Python',
'rating': 2}
{'_id': ObjectId('5def9b07bd101103e4fcb866'),
'age': 24,
'author': 'Tanmay Tamore',
'course': 'Ethical Hacking',
'rating': 3}
{'_id': ObjectId('5dee451be59a39bf5e67a6fa'),
'age': 23,
'author': 'Ben Thomas',
'course': 'HTML, CSS',
'rating': 4}
{'_id': ObjectId('5dee3c828d178a953eec2ad7'),
'age': 21,
'author': 'Shailesh Bhimanpelli',
'course': 'MongoDB using Python',
'rating': 1}

The limit() method in MongoDB

To limit the results in MongoDB we use the limit() method. The limit() method takes one argument which is an integer. This integer defines how many documents should be returned.

from pymongo import MongoClient

mongo = MongoClient('mongodb://localhost:27017/')

db = mongo.CodeSpeedy

courses = db.courses

result = courses.find().limit(4)

for i in result:
    print(i)

Output

{'_id': ObjectId('5dee3c828d178a953eec2ad7'),
'age': 21,
'author': 'Shailesh Bhimanpelli',
'course': 'MongoDB using Python',
'rating': 1}
{'_id': ObjectId('5dee451be59a39bf5e67a6fa'),
'age': 23,
'author': 'Ben Thomas',
'course': 'HTML, CSS',
'rating': 4}
{'_id': ObjectId('5def3b1b2a61b9be930647ff'),
'age': 30,
'author': 'Sorabh Pant',
'course': 'Java',
'rating': 4}
{'_id': ObjectId('5def3b1b2a61b9be93064800'),
'age': 27,
'author': 'Sahil Shah',
'course': 'jQuery',
'rating': 4}

As we can see here we made the limit value has 4 so only 4 documents are printed in the result.

The complete code.

from pymongo import MongoClient

mongo = MongoClient('mongodb://localhost:27017/')

# CodeSpeedy is the name of the database
db = mongo.CodeSpeedy

# database for courses offered by CodeSpeedy i.e. courses is the name of the collection
courses = db.courses

# Ascending order 1
for i in courses.find().sort('age'):
    print(i)
    
# Ascending order 2
for i in courses.find().sort('age', 1):
    print(i)


# Descending order
for i in courses.find().sort('age', -1):
    print(i)

#Limit in MongoDB
result = courses.find().limit(4)

for i in result:
    print(i)

 

Leave a Reply

Your email address will not be published.