Python MongoDB Sort

Sort the Result – Үр дүнг эрэмбэлэх #

Use the sort() method to sort the result in ascending or descending order.

Үр дүнг өгсөх буюу буух дарааллаар эрэмбэлэхийн тулд sort() аргыг ашиглана.

The sort() method takes one parameter for “fieldname” and one parameter for “direction” (ascending is the default direction).

sort() арга нь “талбарынНэр” болон “чиглэл” гэсэн хоёр параметрийг авдаг (өсөх дараалал нь өгөгдмөл чиглэл).

Example – Жишээ #

Sort the result alphabetically by name:

Үр дүнг цагаан толгойн үсгийн дарааллаар эрэмбэлэх:

import pymongo
myclient = pymongo.MongoClient("mongodb://localhost:27017/")
mydb = myclient["mydatabase"]
mycol = mydb["customers"]
mydoc = mycol.find().sort("name")
for x in mydoc:
  print(x)

Sort Descending – Буурах дарааллаар эрэмбэлэх #

Use the value -1 as the second parameter to sort descending.

Хоёр дахь параметрын утгыг -1 болгон ашиглаж бууруулах дарааллаар эрэмбэлэнэ.

sort(“name”, 1) #ascending – Өсөх
sort(“name”, -1) #descending – Буурах

Example – Жишээ #

Sort the result reverse alphabetically by name:

Цагаан толгойн эсрэг үсгийн дарааллаар үр дүнг эрэмбэлэх:

import pymongo
myclient = pymongo.MongoClient("mongodb://localhost:27017/")
mydb = myclient["mydatabase"]
mycol = mydb["customers"]
mydoc = mycol.find().sort("name", -1)
for x in mydoc:
  print(x)

Powered by BetterDocs

Leave a Reply