+91 81900 98289

MongoDB Sort

This MongoDB Sort lesson is for a beginner. Read the short notes, run each example, then change one name or number and run it again.

sort takes a list of pairs. 1 is ascending and -1 is descending.

Sort before limit when you want the top rows rather than an arbitrary slice.

Example 1: Start here

collection.find().sort("score", -1) matches this order.

collection = [{"name": "Meera", "score": 82}, {"name": "Arun", "score": 91}] # a list; the values stay in this order print(sorted(collection, key=lambda doc: doc["score"], reverse=True)) # name= sets that argument by its name

Example 2: Filter the rows

MongoDB Sort is easier to see as a list of records. The filter keeps every row whose seats value is at least 10.

rows = [{"topic": "MongoDB Sort", "seats": 28}, {"topic": "SQL", "seats": 12}] # a list; the values stay in this order print([row["topic"] for row in rows if row["seats"] >= 10]) # keep the items that pass the test

Example 3: Update one field

An update changes one field and leaves the rest of the record alone. On a database you would run an UPDATE or an update_one for the same change.

row = {"topic": "MongoDB Sort", "seats": 28} # a dictionary; each key has one value row["seats"] = row["seats"] + 1 # change this one field print(row)

Example 4: Count the matches

Counting matches is the idea behind COUNT(*). Here the number 28 appears twice.

rows = [28, 4, 28] # a list; the values stay in this order print(sum(1 for value in rows if value == 28)) # keep the items that pass the test
collection.find().sort("score", -1) matches this order.
Call Now 81900 98289