Sort
, MongoDBDocuments 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.
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).
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.
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')}
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.
Sorting is powerful in MongoDB. We can avoid program complexity by having MongoDB sort the results instead of sorting them in Python.