目录
1,安装pymongo库
2,链接数据库
3,排序
活动地址:CSDN21天学习挑战赛
学习的最大理由是想摆脱平庸,早一天就多一份人生的精彩;迟一天就多一天平庸的困扰。
1,安装pymongo库
root@ubuntu-jason:~# pip install pymongo
WARNING: pip is being invoked by an old script wrapper. This will fail in a future version of pip.
Please see https://github.com/pypa/pip/issues/5599 for advice on fixing the underlying issue.
To avoid this problem you can invoke Python with '-m pip' instead of running pip directly.
Looking in indexes: https://pypi.tuna.tsinghua.edu.cn/simple
Collecting pymongo
Downloading https://pypi.tuna.tsinghua.edu.cn/packages/a6/e5/fb665829198cc6447f516c420d30cf90653514b7fd4656a60339e655dcb5/pymongo-4.1.1-cp36-cp36m-manylinux_2_17_x86_64.manylinux2014_x86_64.whl (462 kB)
|████████████████████████████████| 462 kB 817 kB/s
Installing collected packages: pymongo
Successfully installed pymongo-4.1.1
2,链接数据库
创建数据库连接需要使用MongoClient对象,并且指定连接的IP地址,端口号,创建的数据库名。
from pymongo import MongoClient
def mongodb_init01():
"""数据库连接方式1"""
client = MongoClient(host='127.0.0.1', port=27017)
print(client)
def mongodb_init02():
"""数据库连接方式2"""
uri = "mongodb://{}:{}".format('127.0.0.1', 27017)
client = MongoClient(uri)
print(client)
if __name__ == '__main__':
mongodb_init01()
mongodb_init02()
3,排序
sort()方法可以指定升序或者降序排序
第一个参数为要排序的字段,第二个字段指定排序规则,1为升序,-1为降序,默认为升序
from pymongo import MongoClient
client = MongoClient(host='127.0.0.1', port=27017, tz_aware=True)
# 创建新的数据库
new_database = client.new_database
# 创建一个新的集合
new_collection = new_database.new_collection
mylist = [
{"name": "张飞", "hometown": "蜀国", "age": 30, "sex": "男"},
{"name": "关羽", "hometown": "蜀国", "age": 40, "sex": "男"},
{"name": "刘备", "hometown": "蜀国", "age": 50, "sex": "男"}
]
# 使用insert_many插入多条数据
x = new_collection.insert_many(mylist)
mydoc = new_collection.find().sort("name")
for x in mydoc:
print(x)
电脑没有安装数据库,没办法演示了。



