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 tested code examples. Pages are continually updated to stay current, with code correctness a top priority.
Sam Allen is passionate about computer languages. In the past, his work has been recommended by Apple and Microsoft and he has studied computers at a selective university in the United States.
This page was last updated on May 18, 2023 (edit).