Sorting

Introduction to MongoDB in Python

Donny Winston

Donny Winston

Sorting post-query with Python

docs = list(db.prizes.find({"category": "physics"}, ["year"]))

print([doc["year"] for doc in docs][:5])
['2018', '2017', '2016', '2015', '2014']
from operator import itemgetter

docs = sorted(docs, key=itemgetter("year"))
print([doc["year"] for doc in docs][:5])
['1901', '1902', '1903', '1904', '1905']
docs = sorted(docs, key=itemgetter("year"), reverse=True)
print([doc["year"] for doc in docs][:5])
['2018', '2017', '2016', '2015', '2014']
Introduction to MongoDB in Python

Sorting in-query with MongoDB

cursor = db.prizes.find({"category": "physics"}, ["year"],
                        sort=[("year", 1)])
print([doc["year"] for doc in cursor][:5])
['1901', '1902', '1903', '1904', '1905']
cursor = db.prizes.find({"category": "physics"}, ["year"],
                        sort=[("year", -1)])
print([doc["year"] for doc in cursor][:5])
['2018', '2017', '2016', '2015', '2014']
['2018', '2017', '2016', '2015', '2014']
Introduction to MongoDB in Python

Primary and secondary sorting

for doc in db.prizes.find(
        {"year": {"$gt": "1966", "$lt": "1970"}},
        ["category", "year"],
        sort=[("year", 1), ("category", -1)]):
    print("{year} {category}".format(**doc))
1967 physics
1967 medicine
1967 literature
1967 chemistry
1968 physics
1968 peace
1968 medicine
1968 literature
1968 chemistry
1969 physics
1969 peace
1969 medicine
1969 literature
1969 economics
1969 chemistry
Introduction to MongoDB in Python

Sorting with pymongo versus MongoDB shell

In MongoDB shell:

  • Example sortargument: {"year": 1, "category": -1}
  • JavaScript objects retain key order as entered

In Python (< 3.7):

{"year": 1, "category": 1}
{'category': 1, 'year': 1}
[("year", 1), ("category", 1)]
[('year', 1), ('category', 1)]
Introduction to MongoDB in Python

Let's get sorted!

Introduction to MongoDB in Python

Preparing Video For Download...