python使用pymongo與MongoDB基本交互操作示例
本文實例講述了python使用pymongo與MongoDB基本交互操作。分享給大家供大家參考,具體如下:
本文內容: pymongo的使用: 安裝模塊 導入模塊 連接mongod 獲取切換數據庫 選擇集合 CRUD操作首發時間:2018-03-18 20:11
pymongo的使用: 安裝模塊:pip3 pymongo 導入模塊:
import pymongo 連接mongod:
conn=pymongo.MongoClient(host='localhost',port=27017) 獲取切換數據庫:
# db=conn.School #獲取School數據庫 db=conn[’School’] #獲取School數據庫 選擇集合:
# collection=db.teacher#選擇teacher集合 collection=db[’teacher’]#選擇teacher集合 CRUD操作:【pymongo的方法與mongo的命令基本一致,名字類似的功能也類似,參數可以參考mongo的命令,以及源碼說明】 查看文檔: find():返回值是一個Cursor類型的,需要迭代這個返回值才能獲取結果 find_one():返回值是查找結果
importpymongo conn=pymongo.MongoClient(host='localhost',port=27017) db=conn[’School’] collection=db[’teacher’] rel=collection.find() print([r for r in rel]) rel=collection.find({'name':'Alex'}) print([r for r in rel]) # rel=collection.find({'age':{'$gt':20}}) rel=collection.find({'$or':[{'name':'Amy'},{'name':'Alex'}]}) print([r for r in rel]) rel=collection.find_one({'name':'jack'}) print(rel) print(rel[’name’])#單個文檔情況下可用來取出指定值 conn.close() 插入文檔: insert():插入單條文檔,可選,多條文檔使用列表插入,已經不建議使用 insert_one():插入單條文檔 insert_many():插入多條文檔
importpymongo conn=pymongo.MongoClient(host='localhost',port=27017) db=conn[’School’] collection=db[’teacher’] collection.insert({'name':'Job','course':'career'}) # col.insert(document)#**DEPRECATED** - Use :meth:`insert_one` or :meth:`insert_many` instead.#insert是不推薦用了,建議使用insert_one,insert_many collection.insert_one({'name':'Job1','course':'career1'}) t1={'name':'Job2','course':'career2'} t2={'name':'Job3','course':'career3'}collection.insert_many([t1,t2])conn.close() 修改文檔: update():修改單條或多條文檔,由選項multi決定,但已不推薦使用該方法,建議使用update_one()、update_many() update_one():修改單條文檔 update_many():修改多條文檔
importpymongo conn=pymongo.MongoClient(host='localhost',port=27017) db=conn[’School’] collection=db[’teacher’] # rel=collection.update({'name':'Job1'},{ '$set':{'name':'Bob'}})#不推薦使用#collection.update_one({'name':'Job'},{ '$set':{'name':'Bob'}}) collection.update_many({'name':'Job1'},{ '$set':{'name':'Bob'}})conn.close() 刪除文檔: remove():刪除指定文檔,但已經不建議使用,建議使用delete_one和delete_many delete_one(): 刪除符合條件的一條文檔 delete_many():刪除符合條件的所有文檔
importpymongo conn=pymongo.MongoClient(host='localhost',port=27017) db=conn[’School’] collection=db[’teacher’] # collection.remove({'name':'Bob'})#collection.delete_one({'name':'Bob2'}) collection.delete_many({'name':'Job3'})conn.close()
想了解更多,可以參考pymongo官方文檔:http://api.mongodb.com/python/current/api/pymongo/
更多關于Python相關內容感興趣的讀者可查看本站專題:《Python常見數據庫操作技巧匯總》、《Python數學運算技巧總結》、《Python數據結構與算法教程》、《Python函數使用技巧總結》、《Python字符串操作技巧匯總》、《Python入門與進階經典教程》及《Python文件與目錄操作技巧匯總》
希望本文所述對大家Python程序設計有所幫助。
相關文章:
