Home
MongoDB
sort Example
Updated May 18, 2023
Dot Net Perls
Sort, MongoDB. Documents in MongoDB are not returned in a sorted order by default. But we can use sort() on a find() query to order them by a field.
Sorting details. To sort, we call sort() with a field name and an integer. We can use -1 for descending (high to low) and 1 for ascending (low to high).
Example program. Here we create a MongoClient and add 3 documents to it. Each document represents a search engine. We use insert_many to add the 3 documents.
Start We query our "items" collection for "web" search engines. This will return all 3 in our database.
Next We sort the search engines by their popularity. The first argument to sort is the field name we want to sort by.
And The second argument to the sort() method is an integer for descending (which is -1).
from pymongo import MongoClient client = MongoClient("mongodb://127.0.0.1:27017") db = client.search_engines # Reset. db.items.delete_many({}) # Insert some documents. db.items.insert_many([ {"name": "Bing", "type": "web", "popularity": 10}, {"name": "DuckDuckGo", "type": "web", "popularity": 2}, {"name": "Google", "type": "web", "popularity": 50}, ]) # Find web search engines. # ... Sort from most popular to least popular. # Ascending is 1. # Descending is -1. print("FIND WEB") cursor = db.items.find({"type": "web"}).sort( "popularity", -1) # Print our results. for doc in cursor: print(doc)
FIND WEB {'popularity': 50, 'name': 'Google', 'type': 'web', '_id': ObjectId('59f0ef382514971dbc43c9c2')} {'popularity': 10, 'name': 'Bing', 'type': 'web', '_id': ObjectId('59f0ef382514971dbc43c9c0')} {'popularity': 2, 'name': 'DuckDuckGo', 'type': 'web', '_id': ObjectId('59f0ef382514971dbc43c9c1')}
Notes, results. For simple queries, we could sort in Python, without using MongoDB to sort. But when we use a limit() clause, sorting at the level of the database is better.
A summary. Sorting is powerful in MongoDB. We can avoid program complexity by having MongoDB sort the results instead of sorting them in Python.
Dot Net Perls is a collection of pages with code examples, which are updated to stay current. Programming is an art, and it can be learned from examples.
Donate to this site to help offset the costs of running the server. Sites like this will cease to exist if there is no financial support for them.
Sam Allen is passionate about computer languages, and he maintains 100% of the material available on this website. He hopes it makes the world a nicer place.
This page was last updated on May 18, 2023 (edit).
Home
Changes
© 2007-2025 Sam Allen