>本文回答了您在MongoDB中執行CRUD(創建,閱讀,更新,刪除)操作的問題,專注於最佳實踐,處理大型數據集,避免常見的陷阱,並避免常見的陷阱。存儲在靈活的類似JSON的文檔中。 使用您選擇的MongoDB驅動程序(例如Node.js驅動程序,Python的Python的Pymongo,Java驅動程序)執行CRUD操作。 讓我們檢查每個操作:
create(insert):insertOne()
insertMany()
import pymongo myclient = pymongo.MongoClient("mongodb://localhost:27017/") mydb = myclient["mydatabase"] mycol = mydb["customers"] mydict = { "name": "John", "address": "Highway 37" } x = mycol.insert_one(mydict) print(x.inserted_id) #Prints the inserted document's ID mydocs = [ { "name": "Amy", "address": "Apple st 652"}, { "name": "Hannah", "address": "Mountain 21"}, { "name": "Michael", "address": "Valley 345"} ] x = mycol.insert_many(mydocs) print(x.inserted_ids) #Prints a list of inserted document IDs
find()
findOne()
myquery = { "address": "Mountain 21" } mydoc = mycol.find(myquery) for x in mydoc: print(x) mydoc = mycol.find_one(myquery) print(mydoc)
updateOne()
updateMany()
方法更新一個文檔。 $set
更新多個文檔。 您使用myquery = { "address": "Valley 345" } newvalues = { "$set": { "address": "Canyon 123" } } mycol.update_one(myquery, newvalues) myquery = { "address": { "$regex": "^V" } } newvalues = { "$set": { "address": "updated address" } } mycol.update_many(myquery, newvalues)
deleteOne()
deleteMany()
delete:myquery = { "address": "Canyon 123" } mycol.delete_one(myquery) myquery = { "address": { "$regex": "^M" } } x = mycol.delete_many(myquery) print(x.deleted_count)
方法刪除單個文檔。 "mongodb://localhost:27017/"
刪除多個文檔。
insertMany()
and updateMany()
to reduce the number of round trips to the database.$where
>子句,因為它們可能會很慢。利用適當的查詢操作員。 $where
使用更改流實時監視數據中的更改。 這有助於構建對數據更新響應的反應性應用程序。 $where
>忽略數據驗證:
在插入數據之前未能驗證數據和 >以上是mongodb如何增刪改查語句的詳細內容。更多資訊請關注PHP中文網其他相關文章!