Introduction to MongoDB in Python
Donny Winston
Donny Winston
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']
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']
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
In MongoDB shell:
sort
argument: {"year": 1, "category": -1}
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