day107:MoFang:Python操作MongoDB数据库:PyMongo
目录
PyMongo
1.PyMongo安装
pip install pymongo
2.数据库连接
1.数据库连接,无密码
import pymongo mongo = pymongo.MongoClient("mongodb://127.0.0.1:27017/")
2.数据库连接,有密码
# 方式1: import pymongo from urllib import parse username = parse.quote_plus('mofang') # 对用户名进行编码 password = parse.quote_plus('123456') # 对密码进行编码 database = "mofang" # 数据库名称 host = "127.0.0.1" port = "27017" mongo = pymongo.MongoClient('mongodb://%s:%s@%s:%s/%s' % ( username, password, host, port, database)) # 方式2: import pymongo from urllib import parse username = parse.quote_plus('mofang') # 对用户名进行编码 password = parse.quote_plus('123456') # 对密码进行编码 database = "mofang" # 数据库名称 mongo = pymongo.MongoClient('mongodb://127.0.0.1:27017') # 组装成url进行连接 my_db = mongo["mofang"] my_db.authenticate(username,password) # 方式3: import pymongo from urllib import parse username = parse.quote_plus('root') # 对用户名进行编码 password = parse.quote_plus('123456') # 对密码进行编码 host = "127.0.0.1" port = "27017" database = "mofang" # 数据库名称 mongo = pymongo.MongoClient('mongodb://%s:%s@%s:%s/admin' % ( username, password, host, port)) my_db = mongo[database] my_collection = my_db["my_collection"] # 没有往集合里面保存文档之前,mongdb不会真正创建集合!
3.数据库管理
import pymongo # 数据库连接 mongo = pymongo.MongoClient("mongodb://127.0.0.1:27017/") # 创建数据库 my_db = mongo["my_db"] # 没有往集合里面保存文档之前,mongdb不会真正创建集合! # 查看数据库列表 print(mongo.list_database_names()) # 上面的 my_db 因为没有内容,所以没有被创建的。 # 数据库的删除,仅仅是清空所有集合就可以了
4.集合管理
import pymongo mongo = pymongo.MongoClient("mongodb://127.0.0.1:27017/") my_db = mongo["my_db"] my_collection = my_db["my_collection"] # 没有往集合里面保存文档之前,mongdb不会真正创建集合! # 查看集合列表 print(my_db.list_collection_names()) '''删除集合''' # 方式11. my_collections = my_db["notify_list"] my_collections.drop() # 删除成功返回true,如果集合不存在,返回false # 方式2 my_db.drop_collection("notify_list")
5.文档管理
1.添加文档
from pymongo import MongoClient connect = MongoClient("mongodb://127.0.0.1:27017") my_db = connect["mofang"] my_collections = my_db["my_collections"] # 添加一条数据 document = { "name": "xiaoming", "mobile": "13012345678","age":16,"sex":True} ret = my_collections.insert_one(document) print(ret.inserted_id) # 返回主键ID # 添加多条数据 data_list = [ { "name": "xiaobai", "mobile": "13322345678","age":16,"sex":False}, { "name": "xiaohei", "mobile": "13322345678","age":20,"sex":True}, { "name": "xiaohong", "mobile": "13322345678","age":13,"sex":False}, { "name": "xiaolan", "mobile": "13322345678","age":17,"sex":True}, { "name": "xiaolv", "mobile": "13322345678","age":17,"sex":True}, { "name": "xiaolong", "mobile": "13322345678","age":16,"sex":False}, { "name": "xiaofei", "mobile": "13322345678","age":18,"sex":True}, ] ret = my_collections.insert_many(data_list) print(ret.inserted_ids)
2.查询文档
import pymongo mongo = pymongo.MongoClient("mongodb://127.0.0.1:27017/") my_db = mongo["my_db"] my_collection = my_db["my_collection"] # 查看一个文档 ret = my_collection.find_one() # 查询不到则返回None print(ret) # 查看所有文档 for document in my_collection.find(): # 查询不到,返回空列表 print(document) # 查看文档部分字段,find和find_one的第二个参数表示控制字段的显示隐藏,1为显示,0为隐藏 for document in my_collection.find({},{ "_id": 0, "name": 1, "mobile": 1 }): print(document) # 条件查询 query = { "age": 18 } document_list = my_collection.find(query) # find_one则返回一个文档 for document in document_list: print(document) # 比较运算符 query = { "age": {"$gt":17} } document_list = my_collection.find(query) for document in document_list: print(document) # 排序显示 # 单个字段排序: ''' sort("键", 1) 升序 sort("键",-1) 降序 ''' # 多个字段排序: ''' sort([("键1",1),("键2",-1)]) ''' document_list = my_collection.find().sort("age") for document in document_list: print(document) # 限制查询结果数量 document_list = my_collections.find().limit(3) print(document_list)
3.删除文档
import pymongo mongo = pymongo.MongoClient("mongodb://127.0.0.1:27017/") my_db = mongo["my_db"] my_collection = my_db["my_collection"] # 删除一个文档 query = {"name":"xiaoming"} my_collection.delete_one(query) # 删除多个文档 query = { "mobile": {"$regex": "^130"} } ret = my_collection.delete_many(query) print("删除了%d个文档" % ret.deleted_count) # 查询一条数据出来并删除 # 返回一条数据,如果没有,则返回None query = {"name":"xiaobai"} document = my_collection.find_one_and_delete(query) print(document) # {'_id': ObjectId('5fd1e9f17ee514c5ea91823c'), 'name': 'xiaobai', 'mobile': '13322345678', 'age': 16, 'sex': False}
4.更新文档
from pymongo import MongoClient # 数据库链接,必须保证当前系统能正常访问mongodb!!! connect = MongoClient("mongodb://root:123@127.0.0.1:27017/admin") my_db = connect["mofang"] my_collection = my_db["my_collections"] """更新文档""" """按条件更新一个文档的指定数据""" query = { "name": "xiaofei" } upsert = { "$set": { "age": 22 } } ret = my_collection.update_one(query, upsert) print(ret.modified_count) # 0 表示没有任何修改,1表示修改成功 """按条件累加/累减指定数值一个文档的指定数据""" query = { "name": "xiaofei" } upsert = { "$inc": { "age": -1 } } # 累减 # upsert = { "$inc": { "age": 1 } } # 累加 ret = my_collection.update_one(query, upsert) print(ret.modified_count) """更新多条数据""" # 把所有以"133"开头的手机码号的文档,全部改成15012345678 query = { "mobile": {"$regex":"^150"} } upsert = { "$set": { "mobile": "18512345678" } } ret = my_collection.update_many(query, upsert) print(ret.modified_count)