Python MongoDB常用操作

2021-08-04 04:47:06 字數 1531 閱讀 2292

mongodb 是乙個基於分布式檔案儲存的資料庫。由c++語言編寫。旨在為web應用提供可擴充套件的高效能資料儲存解決方案。

mongodb 是乙個介於關聯式資料庫和非關聯式資料庫之間的產品,是非關聯式資料庫當中功能最豐富,最像關聯式資料庫的。他支援的資料結構非常鬆散,是類似json的bson格式,因此可以儲存比較複雜的資料型別。mongo最大的特點是他支援的查詢語言非常強大,其語法有點類似於物件導向的查詢語言,幾乎可以實現類似關聯式資料庫單錶查詢的絕大部分功能。接下來記錄一下在使用pymongo操作mongodb

pip install pymongo
# 獲取mongodb操作,localhost為host,27017為mongodb預設port

client = pymongo.mongoclient("mongodb://localhost:27017/")

# 操作test資料庫

db = client.test

# 獲取student集合

student = db.student

# 插入一條資料,並獲取返回結果

res = student.insert_one()

# 獲取插入之後該條資料的id

object_id = res.inserted_id

print(object_id)

# 插入9條資料

res = student.insert_many([ for

index in range(1,10)])

# 獲取插入之後該9條資料的ids,object_ids為乙個list

object_ids = res.inserted_ids

print(object_ids)

# 查詢單條資料,res為乙個dict

res = student.find_one()

# 查詢滿足條件的所有資料,res為乙個pymongo.cursor.cursor物件

res = student.find()

# 獲取資料個數

print(res.count())

forindex in res:

# index為乙個dict。注意:這個迴圈只能進行一次,如需再次操作返回結果,需要在find一次,或將list(res),將這個返回結果儲存起來

print(index)

# 查詢並更新。為查詢條件;}更新資料;upsert=false找不到不插入資料,upsert=true找不到則插入資料

# res為返回結果,res為乙個字典物件,是之前資料的字典

res = student.find_one_and_update(,},upsert=false)

student.delete_one()
student.delete_many()
更多mongodb的操作:

Python Mongodb資料儲存

導言 一直在用mysql,聽說mongodb非常不錯,一直在工作中沒用到,這個週末來玩玩 mongodb安裝mongodb 管理工具 rockmongo python mongodb操作 coding utf 8 import pymongo client pymongo.mongoclient l...

Python MongoDB 筆記 增刪改查

client mongoclient mongodb localhost 27017 db client.testcollection db.studentsstudent1 student2 單條 result collection.insert one studentl print result...

python mongoDB資料庫操作

目錄 連線和使用資料庫 資料的增刪改查 python與mongodb資料庫互動,在連線資料庫前先啟動資料庫服務 net start mongodb python連線mongodb時需要安裝pymongo庫 pip install pymongo import pymongo 匯入模組 client ...