当前位置:Gxlcms > 数据库问题 > 左手Mongodb右手Redis 通过python连接mongodb

左手Mongodb右手Redis 通过python连接mongodb

时间:2021-07-01 10:21:17 帮助过:2人阅读

""" 2 通过python连接mongodb数据库 3 首先需要初始化数据库连接 4 """ 5 # 使用url统一资源标识符来指定链接地址 6 # mongodb://username:password@ip:端口 7 # 如果没有设定权限验证,则不需要密码 8 # mongodb://ip:端口 ,默认端口27017 :http://localhost:27017/ 9 10 from pymongo import MongoClient 11 12 # client = MongoClient("mongodb://localhost:27017") 13 client = MongoClient(host="localhost", port=27017) 14 # 指定数据库和集合名称 15 db_name = "chapter_3" 16 collection_name = example_data_1 17 # 数据库名 18 database = client[db_name] 19 # 相当于关系型数据库表名,表示数据库中的哪个表 20 collection = database[collection_name] 21 # 插入操作 22 # collection.insert({‘name‘: ‘王小六‘, ‘age‘: 24, ‘work‘: ‘厨师‘}) 23 # 更新 24 # collection.update({"name": "王小六"}, {"$set":{"address": "重庆"}}) 25 # 查询操作 26 # rows = collection.find({}, {"_id": 0}) 27 rows = collection.find({}) 28 for row in rows: 29 # print(row[‘name‘]) 30 print(row) 31 # 删除name = 18030.0 32 # 先查询,后删除 33 # result = collection.delete_one({"name": 18030}) 34 result = collection.find({"name": 18030}) 35 print(type(result)) 36 # upsert更新插入 37 # 如果有数据,则更新,否则插入 38 # 在python中,不存在为None,在mongodb,不存在为null. 39 # db.getCollection(‘example_data_1‘).find({"work":null}) 40 results = collection.find({"work": None}) 41 for result in results: 42 print(result)

 

左手Mongodb右手Redis 通过python连接mongodb

标签:表示   mon   none   for   密码   client   god   资源   cti   

人气教程排行