连接MongoDB
1. 下载模块
pip install pymongo
2. 连接MongoDB
import pymongo
conn = pymongo.MongoClient("127.0.0.1", 27017)
MONGO_DB = conn["DBNAME"] # 增加一个数据库
MongoDB的增删改查
增
1. 普通增加
MONGO_DB.users.insert_one({"name": "alex", "age": 1}) # int类型为 int32
MONGO_DB.users.insert_many([{"name": "alex"}, {"name": "wusir"}])
2. 高级操作
res = MONGO_DB.users.insert_one({"name":"mjj","age": 32,"hobby":["小萝莉", "小妹妹",]})
print(res, dir(res), res.inserted_id)
'''
<pymongo.results.InsertOneResult object at 0x000001DA0BF14348> 生成器
[ ... '__dir__', ... '__str__','inserted_id']
res.inserted_id 5c9b28a00b55621bd860cd58
'''
ress = MONGO_DB.users.insert_many([
{"name":1,"package":[{"name": "屠龙", "act": 999, "p": "强力攻击"},
{"name": "倚天", "act": 998, "p": "迅速突刺"}, ]},
{"name": 2, "package": [{"name": "屠龙", "act": 999, "p": "强力攻击"},
{"name": "倚天", "act": 998, "p": "迅速突刺"}, ]},
{"name": 3, "package": [{"name": "屠龙", "act": 999, "p": "强力攻击"},
{"name": "倚天", "act": 998, "p": "迅速突刺"}, ]}])
查 / 更新
1. 普通查询
res = MONGO_DB.users.find_one({"age": 1}, {"_id": 0})
print(res, type(res)) # {'name': 'alex', 'age': 1} <class 'dict'>
ress = list(MONGO_DB.users.find({},{'id': 0})) # find({})生成器
# 或者利用for循环取值
for item in ress:
print(item)
res = list(MONGO_DB.users.find({"$or":[{"name":"wusir"},{"age":1},{"_id":0}]}))
res = list(MONGO_DB.users.find({"name": {"$in": ["alex", "wusir"]}}))
2. 高级操作: 卖掉'大宝剑'换为'99元宝'
user_info = MONGO_DB.users.find_one({"name": 1})
i = 0
for index, item in enumerate(user_info.get('package')):
if item.get("name") == '大宝剑':
i = index
user_info["package"].pop(i) # 找到索引下标, 并删除
if user_info.get("元宝"):
user_info["元宝"] += 99
else:
user_info["元宝"] = 99
MONGO_DB.users.update_one({'_id': user_info.get('_id')}, {"$set": user_info})
删
1. 删除数据
MONGO_DB.users.delete_one({"name":3})
MONGO_DB.users.delete_many({"name": "alex"})
"_id" 的转换
1. 要注意 MongoDB中获取的 _id 与 字符串的转换
from bson import ObjectId
res = MONGO_DB.users.find_one({"name":2})
_id = str(res.get("_id")) # "_id" 的类型为 <class 'bson.objectid.ObjectId'>
res_json = json.dumps(res) # 对id进行强转str, 再进行json序列化
# 当对 "_id" 进行查询时, 需要对 str的 "_id" 转化为 ObjectId()类型进行查询
res = MONGO_DB.users.find_one({"_id":ObjectId('5c9b2bd70b55622eb05cb5b1')})