python操作mongo数据库基础用法

# pip install pymongo
from bson import ObjectId
from pymongo import MongoClient


# 文档 https://www.runoob.com/python3/python-mongodb.html
# myclient = pymongo.MongoClient('mongodb://localhost:27017/')

client = MongoClient('localhost', 27017)  # 连接本地mongodb数据库,无密码
db = client.taozhentest   # 链接数据库taozhentest
collection = db.taozhentest  # 表(集合)也是taozhentest

# 插入字典数据
mydict = {"name": "ezreal",
             "age": "27",
             "sex": "男",
             "test": ''}

collection.insert_one(mydict)  # 插入一条字典数据

# 查数据  item = collection.find({'name': '菜鸟教程'})
# collection.find({'HeWeather5.basic.city': '北京'})  # 如果数据  json是多层的,就用这样的形式找
for item in collection.find({'name': 'ezreal'}):
    print(item)

# item_data = {'_id': ObjectId('5d7c5c581521034b822198c9'), 'name': 'ezreal', 'age': '27', 'sex': '男'}
# 搜索出记录是如此的
#  {'_id': ObjectId('5d7c5c581521034b822198c9'), 'name': 'ezreal', 'age': '27', 'sex': '男'}

# update数据
collection.update_one({'_id': ObjectId('5d7c5d189d70d240f701cbb3')},
                      {'$set': {'name': "ereal_update", 'age': "28"}})

# 删除数据
result = collection.delete_one({'name': 'ereal_update'})
result1 = collection.delete_one({'_id': ObjectId("5d7c709ea8c023df0772409c")})

print(result)
print(result.deleted_count)  # 删除数量
上一篇:vmware workstation安装uos系统(超祥细)


下一篇:UOS如何格式化U盘