pymongo的常用方法

警告:不要安裝“bson”包。PyMongo自帶bson軟件包,執(zhí)行“pip install bson”或“easy_install bson”會安裝與PyMongo不兼容的第三方軟件包。

一、安裝pymongo

1、用pip進行安裝

pip install pymongo

2、用easy_install進行安裝

easy_install pymongo

二、使用

在使用之前,確保已經(jīng)安裝了mongoDB

1、建立連接

import pymongo

mongo = pymongo.MongoClient('localhost',27017) #連接實例

db_test = mongo['test'] # 連接test庫

table_test=db_test['table_test']? #連接table_test表

2、插入一條數(shù)據(jù)

return_id=table_test.insert_one({'name':'測試名字','content':'測試內(nèi)容'})

3、插入一條數(shù)據(jù)并返回_id

return_id=table_test.insert_one({'name':'測試名字','content':'測試內(nèi)容'}).inserted_id

4、批量插入數(shù)據(jù)

data=[{ "name":"測試2", "content":"測試2" }, { "name":"測試3", "content":"測試4" }]

insert_all=table_test.insert_many(data)

5、批量插入數(shù)據(jù)并返回_id

insert_all=table_test.insert_many(data).inserted_ids

5、查詢一條數(shù)據(jù)

find_content = table_test.find_one({'name':'測試名字'})?

6、通過ObjectId查詢

注意:需在頂部引用from bson.objectid import ObjectId

find_content=table_test.find_one({'_id':ObjectId('5a4097b5c2ca13014c44ff48')})

7、查詢所有數(shù)據(jù)

for find in table_test.find():

? ? ? print(find)

8、計數(shù)

count = table_test.find().count()

9、添加索引

result=table_test.create_index([('name',pymongo.ASCENDING)],unique=True)

10、查看索引

result = sorted(list(table_test.index_information()))

11、刪除一條數(shù)據(jù)

result=table_test.delete_one({'name':'測試3'})

12、批量刪除

result=table_test.delete_many({'name':'測試2'})

13、修改一條數(shù)據(jù)

result=table_test.find_one_and_update({'name':'測試名字1'},{'$set':{'name':'1'}})

修改器:$set:例如把“測試名字1”修改成“1”

$unset:顧名思義,刪除,例如把“測試名字1”刪除,是把整個name字段刪除了,而不是把name字段的內(nèi)容清空

$inc: 增加已有鍵的值, 或者在鍵不存在時創(chuàng)建一個鍵,例如我的年齡是18歲,我想增加2歲,{'$inc':{'age':2}}

以上只是一些比較常用到的方法,如果有不明白的地方,可以給我留言。

python小白一只,歡迎各位大佬指點

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

  • .. currentmodule:: motor.motor_asyncio Tutorial: Using Mo...
    yutiansut閱讀 4,049評論 0 0
  • 1. Java基礎(chǔ)部分 基礎(chǔ)部分的順序:基本語法,類相關(guān)的語法,內(nèi)部類的語法,繼承相關(guān)的語法,異常的語法,線程的語...
    子非魚_t_閱讀 34,740評論 18 399
  • 本教程適合于mongodb的創(chuàng)建/查詢/和基本的案例操作注:未經(jīng)許可不得轉(zhuǎn)載 一、配置和安裝相應(yīng)的環(huán)境 主要針對p...
    tianmh閱讀 18,558評論 3 19
  • 我們是宇宙中的一顆星辰 你并不知道生活中什么時候就突然改變了方向 你被失望拖進深淵 你被疾病拖進墳?zāi)?你被挫折踐踏...
    尤物嘉爾閱讀 3,926評論 0 5
  • 你的青春是否也曾放肆地奔走? 像蒲公英一樣的不問路途 你的心中是否也曾被回憶填充? 像從來沒有經(jīng)歷過的蜃樓 你的率...
    封月殘夕閱讀 297評論 2 3

友情鏈接更多精彩內(nèi)容