python操作MongoDB


連接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')})


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM