# 安装 pymongo :pip install pymongo
import pymongo
try:
# 1、链接mongodb服务
mongo_py = pymongo.MongoClient()
# 2、库和表的名字;有数据会自动建库建表
'''
建库建集合(表)第一种方法
'''
# # 数据库
# db = mongo_py['newdb']
# # 集合
# collection = db['stu']
'''
建库建集合(表)第二种方法
'''
# collection = mongo_py["newdb"]["stu"]
collection = mongo_py.newdb.stu
# 3、插入数据
one = {"name":"张三","age":55}
two_many = [
{"name": "张三", "age": 55},
{"name": "李四", "age": 50},
{"name": "王五", "age": 30},
{"name": "小刘", "age": 20},
{"name": "小菜", "age": 15}
]
three_many = [
{"name":"xiaowang","age":50},
{"name": "xiaowang", "age": 40},
{"name": "xiaowang", "age": 30},
{"name": "xiaowang", "age": 20}
]
# collection.insert_one(one)
# collection.insert_many(three_many)
# collection.insert() # 一个或多个
# 4、删除数据
# collection.delete_one({"age":15})
# collection.delete_many({"age": 55})
# 5、修改数据
# collection.update_one({"age":20},{"$set":{"name":"刘一"}})
# collection.update_many({"name":"xiaowang"},{"$set":{"age":100}})
# 6、查询数据
result = collection.find({"age":100})
for i in result:
print(i)
except Exception as e:
print(e)
finally:
# 4、关闭数据库
mongo_py.close()
mongo和python的交互
最新推荐文章于 2024-04-27 08:54:00 发布