文章目录
- @[toc]
- 数据插入
- 数据查询
- 数据更新
- 数据删除
文章目录
- @[toc]
- 数据插入
- 数据查询
- 数据更新
- 数据删除
个人主页:丷从心·
系列专栏:Python数据库
学习指南:Python学习指南
数据插入
from pymongo import MongoClient
def insert_data():
mongo_client = MongoClient(host='localhost', port=27017)
collection = mongo_client['python_database']['book_info']
try:
collection.insert_many([{'id': 1, 'name': '射雕英雄传', 'pub_date': '1980-5-1', 'read_count': 12,
'comment_count': 34, 'is_delete': 0},
{'id': 2, 'name': '天龙八部', 'pub_date': '1986-7-24', 'read_count': 36,
'comment_count': 40, 'is_delete': 0},
{'id': 3, 'name': '笑傲江湖', 'pub_date': '1995-12-24', 'read_count': 20,
'comment_count': 80, 'is_delete': 0},
{'id': 4, 'name': '雪山飞狐', 'pub_date': '1987-11-11', 'read_count': 58,
'comment_count': 24, 'is_delete': 0}])
except Exception as e:
print(f'数据插入失败: {e}')
else:
print('数据插入成功...')
if __name__ == '__main__':
insert_data()
-
mongo_client = MongoClient(host='localhost', port=27017)
用于连接数据库host
用于指定数据库IP
地址,localhost
表示本地port
用于指定数据库端口
-
collection = mongo_client['python_database']['book_info']
用于指定数据库和数据集合'python_database'
是指定的数据库'book_info'
是指定的数据集合
-
collection.insert_many()
用于插入多条数据
数据查询
from pymongo import MongoClient
def query_data():
mongo_client = MongoClient(host='localhost', port=27017)
collection = mongo_client['python_database']['book_info']
result = collection.find_one({'name': '射雕英雄传'})
if result:
print(result)
else:
print('数据不存在...')
if __name__ == '__main__':
query_data()
数据更新
from pymongo import MongoClient
def update_data():
mongo_client = MongoClient(host='localhost', port=27017)
collection = mongo_client['python_database']['book_info']
collection.update_one({'name': '射雕英雄传'}, {'$set': {'is_delete': 1}})
result = collection.find_one({'name': '射雕英雄传'})
if result:
print(result)
else:
print('数据不存在...')
if __name__ == '__main__':
update_data()
数据删除
from pymongo import MongoClient
def delete_data():
mongo_client = MongoClient(host='localhost', port=27017)
collection = mongo_client['python_database']['book_info']
collection.delete_one({'name': '射雕英雄传'})
result = collection.find()
if result:
for item in result:
print(item)
else:
print('数据不存在...')
if __name__ == '__main__':
delete_data()