PyMongo
安装:
pip install pymongo
一、数据库连接
数据库连接,无密码
from pymongo import MongoClient
# 数据库链接,必须保证当前系统能正常访问mongodb!!!
connect = MongoClient('mongodb://127.0.0.1:27017/')
# 创建/切换数据库,数据库不存在则会库中有文档以后,自动创建
my_db = connect['mofang']
print(my_db) # 数据库信息
# 创建/进入集合,集合不存在则会集合中有文档以后,自动创建
my_collections = my_db['my_collections']
print(my_collections) # 集合信息
数据库连接,有密码
from pymongo import MongoClient
# 数据库链接,必须保证当前系统能正常访问mongodb!!!
"""方式1:如果帐号密码没有特殊字符"""
# connect = MongoClient('mongodb://mofang:123456@127.0.0.1:27017/mofang')
"""方式2:当前库的管理员连接"""
# from urllib import parse
# username = parse.quote_plus('mofang') # 对用户名进行编码
# password = parse.quote_plus('123456') # 对密码进行编码
# database = parse.quote_plus('mofang') # 对数据库进行编码
# connect = MongoClient('mongodb://%s:%s@127.0.0.1:27017/%s' % (username, password, database))
# my_db = connect['mofang']
# my_collections = my_db['my_collections']
"""方式3:基于超级管理员身份连接,不需要当前库的管理员了"""
from urllib import parse
username = parse.quote_plus('root') # 对用户名进行编码
password = parse.quote_plus('123') # 对密码进行编码
database = parse.quote_plus('admin') # 对数据库进行编码
connect = MongoClient('mongodb://%s:%s@127.0.0.1:27017/%s' % (username, password, database))
my_db = connect['mofang']
my_collections = my_db['my_collections']
# 添加一篇文档
data = { 'name': 'xiaoming1号', 'sex': True, 'age':17}
ret = my_collections.insert_one(data)
print(ret.inserted_id)
二、数据库管理
from pymongo import MongoClient
# 数据库链接,必须保证当前系统能正常访问mongodb!!!
connect = MongoClient('mongodb://root:123@127.0.0.1:27017/admin')
my_db = connect['mofang']
my_collecctions = my_db['my_collections']
# 查看所有数据库[除了三个基本数据库以外,其他数据库只会显示有文档数据的]
ret = connect.list_database_names()
print(ret) # ['admin', 'config', 'local', 'mofang']
ret = my_db.list_collection_names()
print(ret) # ['my_collections']
# 数据库的删除,仅仅是清空所有集合就可以了
三、集合管理
from pymongo import MongoClient
# 数据库链接,必须保证当前系统能正常访问mongodb!!!
connect = MongoClient('mongodb://root:123@127.0.0.1:27017/admin')
my_db = connect['mofang']
my_collecctions = my_db['my_collections']
# 查看所有数据库[除了三个基本数据库以外,其他数据库只会显示有文档数据的]
# ret = connect.list_database_names()
# print(ret) # ['admin', 'config', 'local', 'mofang']
# ret = my_db.list_collection_names()
# print(ret) # ['my_collections']
# 删除集合的方式1
my_collecctions = my_db['notify_list']
my_collecctions.drop()
# 删除集合的方式2
my_db.drop_collection('notify_list')
四、文档管理
1.添加文档
from pymongo import MongoClient
# 数据库链接,必须保证当前系统能正常访问mongodb!!!
connect = MongoClient('mongodb://root:123@127.0.0.1:27017/admin')
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.查询文档
from pymongo import MongoClient
# 数据库链接,必须保证当前系统能正常访问mongodb
connect = MongoClient('mongodb://root:123@127.0.0.1:27017/admin')
my_db = connect['mofang']
my_collections = my_db['my_collections']
"""获取一条"""
# document = my_collections.find_one()
# print(document) # {'_id': ObjectId('5fd21237d883925209b60067'), 'name': 'xiaoming1号', 'sex': True, 'age': 17}
# 获取数据中的信息
# print(document['name']) # xiaoming1号
"""获取多条数据"""
# document_list = my_collections.find()
# print(document_list)
# for document in document_list:
# print(document)
# print(document['_id'])
"""字段投影:只显示部分字段,1表示显示,0表示隐藏"""
# document_list = my_collections.find({}, {'name': 1, '_id': 0})
# for document in document_list:
# print(document)
"""基于查询条件获取数据"""
# 值相等
# query = {'name': {'$eq': 'xiaoming'}}
# query = {'name': 'xiaoming'}
# document = my_collections.find_one(query)
# print(document) # {'_id': ObjectId('5fd2184326c8493bb4e2ace3'), 'name': 'xiaoming', 'mobile': '13012345678', 'age': 16, 'sex': True}
""" query = {"age":{"$gt":17}} age > 17 query = {"age":{"$gte":17}} age >= 17 query = {"age":{"$lte":17}} age <= 17 query = {"age":{"$lt":17}} age < 17 query = {"age":{"$ne":17}} age != 17 query = {"age":{"$in":[16,17]}} age in [16,17] """
# query = {'age': {'$in': [16, 18]}}
# document_list = my_collections.find(query)
# for document in document_list:
# print(document)
"""排序"""
""" 单个字段: sort("age",-1) # 倒序 sort("age",1) # 升序 多个字段: sort([("age",-1),("_id",1)]) """
# document_list = my_collections.find().sort('age', -1)
# document_list = my_collections.find().sort([('age', -1), ('_id', 1)])
# for document in document_list:
# print(document)
"""限制结果"""
document_list = my_collections.find().limit(3)
for document in document_list:
print(document)
3.删除文档
from pymongo import MongoClient
# 数据库链接,必须保证当前系统能正常访问mongodb
connect = MongoClient('mongodb://root:123@127.0.0.1:27017/admin')
my_db = connect['mofang']
my_collections = my_db['my_collections']
"""删除文档"""
# 删除一个文档
query = { 'name': 'xiaoming'}
ret = my_collections.delete_one(query)
print(ret.deleted_count) # 1:删除成功 0:没有删除的数据
# 删除多个文档
query = { 'name': 'xiaoming1号'}
ret = my_collections.delete_many(query)
print(ret.deleted_count) # 大于0:删除成功 0:没有删除的数据
# 查询一条数据出来并删除
# 返回一条数据,如果没有,则返回None
query = { 'name': 'xiaobai'}
document = my_collections.find_one_and_delete(query)
print(document) # {'_id': ObjectId('5fd218accf506de09fbecd68'), '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_collections = my_db['my_collections']
"""更新文档"""
"""按条件更新一个文档的指定数据"""
query = { 'name': 'xiaofei'}
upsert = { '$set': { 'age': 22}}
ret = my_collections.update_one(query, upsert)
print(ret.modified_count) # 0 表示没有任何修改,1表示修改成功
"""按条件累加/累减指定数值一个文档的指定数据"""
query = { 'name': 'xiaofei'}
upsert = { '$inc': { 'age': -1}} # 累减
upsert = { '$inc': { 'age': 1}} # 累加
ret = my_collections.update_one(query, upsert)
print(ret.modified_count)
"""更新多条数据"""
# 把所有以"133"开头的手机码号的文档,全部改成15012345678
query = { 'mobile': { '$regex': '^133'}}
upsert = { '$set': { 'mobile': '15012345678'}}
ret = my_collections.update_many(query, upsert)
print(ret.modified_count)
本文地址:https://blog.csdn.net/qq_45957580/article/details/111004227