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

首先需要安装第三方包pymongo

pip install pymongodb

 1 """
 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)
原文地址:https://www.cnblogs.com/hamish26/p/11357072.html