Python MongoDB 排序sort查询介绍

2021年3月11日18:14:37 发表评论 857 次浏览

MongoDB是跨平台的面向文档的数据库程序, 也是最受欢迎的NoSQL数据库程序。 NoSQL的意思是非关系。 MongoDB以键值对的形式存储数据。它是一个开源的文档数据库, 可提供高性能和可伸缩性, 以及企业应用程序中海量数据集的数据建模和数据管理。 MongoDB还提供了自动扩展功能。它使用类似于JSON的文档, 这使得数据库非常灵活且可扩展。

注意:有关更多信息, 请参阅MongoDB和Python

排序MongoDB文件

sort()方法用于按某种顺序对数据库进行排序。此方法接受两个参数, 第一个是字段名, 第二个是用于排序的方向。 (默认情况下, 它以升序排序)

语法如下:

sort(fieldname, direction)

注意:1作为方向用于升序, -1作为方向用于降序

范例1:使用sort()函数按名称字母顺序对结果进行排序。

假设数据库如下所示–

python-mongodb-db
# python code to sort elements
# alphabetically in ascending order
   
import pymongo
  
  
# establishing connection
# to the database
my_client = pymongo.MongoClient( 'localhost' , 27017 )
  
# Name of the databse
mydb = my_client[ "gfg" ]
  
# Name of the collection
mynew = mydb[ "names" ]
   
# sorting function 
mydoc = mynew.find().sort( "name" )
   
for x in mydoc:
     print (x)

输出:

python-mongodb-sort-1

范例2:降序排列

import pymongo
  
  
# establishing connection 
# to the database
my_client = pymongo.MongoClient( 'localhost' , 27017 )
  
# Name of the databse
mydb = my_client[ "gfg" ]
  
# Name of the collection
mynew = mydb[ "names" ]
   
# sorting function with -1 
# as direction
mydoc = mynew.find().sort( "name" , - 1 )
   
for x in mydoc:
     print (x)

输出:

python-mongodb-sort-2

注意怪胎!巩固你的基础Python编程基础课程和学习基础知识。

首先, 你的面试准备可通过以下方式增强你的数据结构概念:Python DS课程。


木子山

发表评论

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: