Movatterモバイル変換


[0]ホーム

URL:


Open In App
Next Article:
Python MongoDB - distinct()
Next article icon

In MongoDB, sorting allows you to arrange documents in a specific order based on one or more fields. Using PyMongo in Python, you can apply thesort() method on a query result to retrieve documents inascendingordescendingorder. This is helpful when you want results ranked by specific fields.

Syntax

collection.find().sort(field, direction)

Parameter:

Let's explore some Examples to understand it.

Sample Collection used in this article:

sort-database
Collection used for Example

Example 1:

This Example sorts documents in the names collection by the "id" field inascendingorder using PyMongo.

Python
importpymongoclient=pymongo.MongoClient('localhost',27017)db=client["GFG"]collection=db["names"]# Sort documents by 'id' in ascending ordersorted_docs=collection.find().sort("id",1)# Print sorted documentsfordocinsorted_docs:print(doc)

Output

sort-output1
Snapshot of Terminal showing Output of sort method

Explanation: find().sort("id", 1) retrieves all documents from the "names" collection and sorts them inascendingorder by the "id" field.

Example 2:

This code retrieves documents from the names collection sorting them by the "name" field indescendingorder using PyMongo.

Python
importpymongomy_client=pymongo.MongoClient('localhost',27017)mydb=my_client["gfg"]mynew=mydb["names"]# Sort documents by 'name' in descending ordermydoc=mynew.find().sort("name",-1)# Print the sorted documentsforxinmydoc:print(x)

Output :

ss
Snapshot of Terminal showing Output of sort method

Explanation: find().sort("name", -1) retrieves all documents from the "names" collection and sorts them indescending order by the "name" field.

Related Article:


Improve
Practice Tags :

Similar Reads

We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood ourCookie Policy &Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences

[8]ページ先頭

©2009-2025 Movatter.jp