pymongo 學習記錄

pymongo 是 mongodb 的 python Driver Editor.
記錄下學習過程中感覺以后會常用多一些部分,以做參考薯酝。

1. 連接數(shù)據(jù)庫

要使用pymongo最先應該做的事就是先連上運行中的 mongod 。

  • 創(chuàng)建一個 .py 文件爽柒,首先導入 pymongo:
from pymongo import MongoClient
  • 創(chuàng)建一個連接到 mongod 到客戶端:
client = MongoClient()
或者:
client = MongoClient("mongodb://mongodb0.example.net:27019")
  • 連接數(shù)據(jù)庫:
# 假設要連接的數(shù)據(jù)庫名為 primer
db = client.primer
或者:
db = client['primer']
  • 連接到對應的數(shù)據(jù)集:
coll = db.dataset
coll = db['dataset']

至此吴菠,已經(jīng)完整對連接了數(shù)據(jù)庫和數(shù)據(jù)集,完成了初識化的操作霉赡。

2. 插入數(shù)據(jù)

> insert_one(document)
> insert_many(documents, ordered=True)
  • insert_one(document)
    在 pymongo 中的插入函數(shù)并不像 mongo shell 中完全一樣橄务,所以需要注意一下:
from datetime import datetime
result = db.restaurants.insert_one(
    {
        "address": {
            "street": "2 Avenue",
            "zipcode": "10075",
            "building": "1480",
            "coord": [-73.9557413, 40.7720266]
        },
        "borough": "Manhattan",
        "cuisine": "Italian",
        "grades": [
            {
                "date": datetime.strptime("2014-10-01", "%Y-%m-%d"),
                "grade": "A",
                "score": 11
            },
            {
                "date": datetime.strptime("2014-01-16", "%Y-%m-%d"),
                "grade": "B",
                "score": 17
            }
        ],
        "name": "Vella",
        "restaurant_id": "41704620"
    }
)

其中返回的結果:result 中是一個:InsertOneResult 類:
class pymongo.results.InsertOneResult(inserted_id, acknowledged)
其中 inserted_id 是插入的元素多 _id 值。

  • insert_many(documents, ordered=True)
result = db.test.insert_many([{'x': i} for i in range(2)])

3. 查詢數(shù)據(jù)

> find(filter=None, projection=None, skip=0, limit=0,
        no_cursor_timeout=False, cursor_type=CursorType.NON_TAILABLE,
        sort=None, allow_partial_results=False, oplog_replay=False,
        modifiers=None, manipulate=True)
> find_one(filter_or_id=None, *args, **kwargs)
  • find
    find 查詢出來的是一個列表集合穴亏。
cursor = db.restaurants.find()
for document in cursor:
    print(document)
# 查詢字段是最上層的
cursor = db.restaurants.find({"borough": "Manhattan"})
# 查詢字段在內層嵌套中
cursor = db.restaurants.find({"address.zipcode": "10075"})
  • 操作符查詢
cursor = db.restaurants.find({"grades.score": {"$gt": 30}})
cursor = db.restaurants.find({"grades.score": {"$lt": 10}})
# AND
cursor = db.restaurants.find({"cuisine": "Italian", "address.zipcode": "10075"})
cursor = db.restaurants.find(
    {"$or": [{"cuisine": "Italian"}, {"address.zipcode": "10075"}]})
  • find_one
    返回的是一個JSON式文檔蜂挪,所以可以直接使用!

  • sort
    排序時要特別注意嗓化,使用的并不是和mongo shell的一樣棠涮,而是使用了列表,
    當排序的標準只有一個刺覆,且是遞增時严肪,可以直接寫在函數(shù)參數(shù)中:

pymongo.ASCENDING = 1
pymongo.DESCENDING = -1
cursor = db.restaurants.find().sort("borough")
cursor = db.restaurants.find().sort([
    ("borough", pymongo.ASCENDING),
    ("address.zipcode", pymongo.DESCENDING)
])

4. 更新文檔

更新文檔的函數(shù)有三個(不能更新 _id 字段)

update_one(filter, update, upsert=False)
update_many(filter, update, upsert=False)
replace_one(filter, replacement, upsert=False) 
find_one_and_update(filter, update, projection=None, sort=None, return_document=ReturnDocument.BEFORE, **kwargs)
  • update_one
    返回結果是一個:UpdateResult,如果查找到多個匹配谦屑,則只更新
    第一個驳糯!
result = db.restaurants.update_one(
    {"name": "Juni"},
    {
        "$set": {
            "cuisine": "American (New)"
        },
        "$currentDate": {"lastModified": True}
    }
)
result.matched_count
10
result.modified_count
1
  • update_many
    查找到多少匹配,就更新多少氢橙。
result = db.restaurants.update_many(
    {"address.zipcode": "10016", "cuisine": "Other"},
    {
        "$set": {"cuisine": "Category To Be Determined"},
        "$currentDate": {"lastModified": True}
    }
)
result.matched_count
20
result.modified_count
20
  • replace_one
result = db.restaurants.replace_one(
    {"restaurant_id": "41704620"},
    {
        "name": "Vella 2",
        "address": {
            "coord": [-73.9557413, 40.7720266],
            "building": "1480",
            "street": "2 Avenue",
            "zipcode": "10075"
        }
    }
)
result.matched_count
1
result.modified_count
1
  • find_one_and_update
    返回更新前的文檔
db.test.find_one_and_update(
    {'_id': 665}, {'$inc': {'count': 1}, '$set': {'done': True}})
{u'_id': 665, u'done': False, u'count': 25}}

5. 刪除文檔

刪除時主要有兩個:

> delete_one(filter)
> delete_many(filter)
> drop()
> find_one_and_delete(filter, projection=None, sort=None, **kwargs)
> find_one_and_replace(filter, replacement, projection=None,
>       sort=None, return_document=ReturnDocument.BEFORE, **kwargs)
  • delete_one
result = db.test.delete_one({'x': 1})
result.deleted_count
1
  • delete_many
result = db.restaurants.delete_many({"borough": "Manhattan"})
result.deleted_count
10259
# 刪除全部
result = db.restaurants.delete_many({})
  • drop()
    刪除整個集合酝枢,是drop_collection()的別名
db.restaurants.drop()
  • find_one_and_delete
db.test.count({'x': 1})
2
db.test.find_one_and_delete({'x': 1})
{u'x': 1, u'_id': ObjectId('54f4e12bfba5220aa4d6dee8')}
db.test.count({'x': 1})
  • find_one_and_replace
>>> for doc in db.test.find({}):
...     print(doc)
...
{u'x': 1, u'_id': 0}
{u'x': 1, u'_id': 1}
{u'x': 1, u'_id': 2}
>>> db.test.find_one_and_replace({'x': 1}, {'y': 1})
{u'x': 1, u'_id': 0}
>>> for doc in db.test.find({}):
...     print(doc)
...
{u'y': 1, u'_id': 0}
{u'x': 1, u'_id': 1}
{u'x': 1, u'_id': 2}

6. 索引操作

索引主要有創(chuàng)建索引和刪除索引:

> create_index(keys, **kwargs)
> create_indexes(indexes)
> drop_index(index_or_name)
> drop_indexes()
> reindex()
> list_indexes()
> index_information()
  • create_index
my_collection.create_index("mike")
my_collection.create_index([("mike", pymongo.DESCENDING),
...                             ("eliot", pymongo.ASCENDING)])
my_collection.create_index([("mike", pymongo.DESCENDING)],
...                            background=True)
  • create_indexes
>>> from pymongo import IndexModel, ASCENDING, DESCENDING
>>> index1 = IndexModel([("hello", DESCENDING),
...                      ("world", ASCENDING)], name="hello_world")
>>> index2 = IndexModel([("goodbye", DESCENDING)])
>>> db.test.create_indexes([index1, index2])
["hello_world"]
  • drop_index
    index_or_name: 索引編號或者索引的name
my_collection.drop_index("mike")
  • drop_indexs
    刪除所有索引

  • reindex
    重構索引,盡量少用悍手,如果集合比較大多話帘睦,會很耗時耗力.

for index in db.test.list_indexes():
...     print(index)
...
SON([(u'v', 1), (u'key', SON([(u'_id', 1)])),
     (u'name', u'_id_'), (u'ns', u'test.test')])
最后編輯于
?著作權歸作者所有,轉載或內容合作請聯(lián)系作者
  • 序言:七十年代末,一起剝皮案震驚了整個濱河市坦康,隨后出現(xiàn)的幾起案子竣付,更是在濱河造成了極大的恐慌,老刑警劉巖滞欠,帶你破解...
    沈念sama閱讀 216,843評論 6 502
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件古胆,死亡現(xiàn)場離奇詭異,居然都是意外死亡筛璧,警方通過查閱死者的電腦和手機逸绎,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 92,538評論 3 392
  • 文/潘曉璐 我一進店門妖滔,熙熙樓的掌柜王于貴愁眉苦臉地迎上來,“玉大人桶良,你說我怎么就攤上這事【谙瑁” “怎么了陨帆?”我有些...
    開封第一講書人閱讀 163,187評論 0 353
  • 文/不壞的土叔 我叫張陵,是天一觀的道長采蚀。 經(jīng)常有香客問我疲牵,道長,這世上最難降的妖魔是什么榆鼠? 我笑而不...
    開封第一講書人閱讀 58,264評論 1 292
  • 正文 為了忘掉前任纲爸,我火速辦了婚禮,結果婚禮上妆够,老公的妹妹穿的比我還像新娘识啦。我一直安慰自己,他們只是感情好神妹,可當我...
    茶點故事閱讀 67,289評論 6 390
  • 文/花漫 我一把揭開白布颓哮。 她就那樣靜靜地躺著,像睡著了一般鸵荠。 火紅的嫁衣襯著肌膚如雪冕茅。 梳的紋絲不亂的頭發(fā)上,一...
    開封第一講書人閱讀 51,231評論 1 299
  • 那天蛹找,我揣著相機與錄音姨伤,去河邊找鬼。 笑死庸疾,一個胖子當著我的面吹牛乍楚,可吹牛的內容都是我干的。 我是一名探鬼主播彼硫,決...
    沈念sama閱讀 40,116評論 3 418
  • 文/蒼蘭香墨 我猛地睜開眼炊豪,長吁一口氣:“原來是場噩夢啊……” “哼!你這毒婦竟也來了拧篮?” 一聲冷哼從身側響起词渤,我...
    開封第一講書人閱讀 38,945評論 0 275
  • 序言:老撾萬榮一對情侶失蹤,失蹤者是張志新(化名)和其女友劉穎串绩,沒想到半個月后缺虐,有當?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體,經(jīng)...
    沈念sama閱讀 45,367評論 1 313
  • 正文 獨居荒郊野嶺守林人離奇死亡礁凡,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內容為張勛視角 年9月15日...
    茶點故事閱讀 37,581評論 2 333
  • 正文 我和宋清朗相戀三年高氮,在試婚紗的時候發(fā)現(xiàn)自己被綠了慧妄。 大學時的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片。...
    茶點故事閱讀 39,754評論 1 348
  • 序言:一個原本活蹦亂跳的男人離奇死亡剪芍,死狀恐怖塞淹,靈堂內的尸體忽然破棺而出,到底是詐尸還是另有隱情罪裹,我是刑警寧澤饱普,帶...
    沈念sama閱讀 35,458評論 5 344
  • 正文 年R本政府宣布,位于F島的核電站状共,受9級特大地震影響套耕,放射性物質發(fā)生泄漏。R本人自食惡果不足惜峡继,卻給世界環(huán)境...
    茶點故事閱讀 41,068評論 3 327
  • 文/蒙蒙 一冯袍、第九天 我趴在偏房一處隱蔽的房頂上張望。 院中可真熱鬧碾牌,春花似錦康愤、人聲如沸。這莊子的主人今日做“春日...
    開封第一講書人閱讀 31,692評論 0 22
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽。三九已至裤翩,卻和暖如春资盅,著一層夾襖步出監(jiān)牢的瞬間,已是汗流浹背踊赠。 一陣腳步聲響...
    開封第一講書人閱讀 32,842評論 1 269
  • 我被黑心中介騙來泰國打工呵扛, 沒想到剛下飛機就差點兒被人妖公主榨干…… 1. 我叫王不留,地道東北人筐带。 一個月前我還...
    沈念sama閱讀 47,797評論 2 369
  • 正文 我出身青樓今穿,卻偏偏與公主長得像,于是被迫代替她去往敵國和親伦籍。 傳聞我的和親對象是個殘疾皇子蓝晒,可洞房花燭夜當晚...
    茶點故事閱讀 44,654評論 2 354

推薦閱讀更多精彩內容