python操做mongo(2)

更新數據

你能夠經過調用**update_one()和update_many()**方法來更新集合collection中特定的文檔.update_one()一次只能更新一個內容。使用update_many()能夠一次性更新多個文檔內容。python

預備條件

from pymongo import MongoClient

client = MongoClient()
db = client.test

更新高等級字段

下面的操做是更新第一個匹配name爲juni的文檔,經過$set操做來更新cuisine和currentDate字段(更新爲當前的時間)。mongodb

from pymongo import MongoClient

client=MongoClient()
db=client.test

result = db.restaurants.update_one(
	{"name": "Juni"},
	{
		"$set": {
			"cuisine": "American (New)"
		},
		"$currentDate": {"lastModified": True}
	}
)

調用 update_one操做返回的一個UpdateResult對象,表示匹配的文件計數 modified_count表示的是當前修改的總數ui

result.matched_count

將上面的值進行輸出獲得的值爲1rest

更新一個嵌入的文檔

下面的操做是更新一個嵌入的文檔中的一個字段,經過使用.符號來訪問相應的字段名。code

result = db.restaurants.update_one(
	{"restaurant_id": "41156888"},
	{"$set": {"address.street": "East 31st Street"}}
)

上面的操做result表示的是修改的文檔數量對象

更新多個文檔

update_one()一次只能更新一個文檔,能夠經過使用update_many()方法來同時更新多個文件,下面的操做匹配文檔當中全部address.zipcode爲10016和cuisine爲Other的字段,而且設置其cusine爲「Category,而且將lastModified更新爲當前的時間.ip

result = db.restaurants.update_many(
    {"address.zipcode": "10016", "cuisine": "Other"},
    {
        "$set": {"cuisine": "Category To Be Determined"},
        "$currentDate": {"lastModified": True}
    }
)

上面方法返回一個UpdateResult對象,該對象裏面含有匹配的文件個數以及更改文件的計數器。下面的語句返回的爲20,表示上面的操做更新了二十條記錄文檔

result.matched_countio

替換文檔

調用update()方法只是更新特定的字段,而使用replace_one或者replace_many(),將整個匹配的內容更改成你輸入的內容。 好比咱們本來有下面的內容ast

{'cuisine': 'Italian',

'restaurant_id': '41704620',

'name': 'Vella',

'_id': ObjectId('5704d3c3a75b1775d3b2583b'),

'borough': 'Manhattan',

'address': {'coord': [-73.9557413, 40.7720266], 'building': '1480', 'zipcode': '10075', 'street': '2 Avenue'}, 'grades': [{'date': datetime.datetime(2014, 10, 1, 0, 0), 'score': 11, 'grade': 'A'},

{'date': datetime.datetime(2014, 1, 16, 0, 0), 'score': 17, 'grade': 'B'}]}

咱們經過調用 下面的語句

result = db.restaurants.replace_one(
    {"restaurant_id": "41704620"},
    {
        "name": "Vella 2",
        "address": {
            "coord": [-73.9557413, 40.7720266],
            "building": "1480",
            "street": "2 Avenue",
            "zipcode": "10075"
        }
    }
)

這裏咱們再次查詢的時候反正已經不能經過restaurant_id來進行查詢了,由於該記錄已經完成更新爲非典所給出的字段了,這裏查詢的內容以下:

{'_id': ObjectId('5704d3c3a75b1775d3b2583b'),

'name': 'Vella 2',

'address': {'zipcode': '10075', 'building': '1480', 'street': '2 Avenue', 'coord': [-73.9557413, 40.7720266]}}

默認的當一個update操做沒有任何匹配的數據時,mongo什麼都不會去作。可是咱們能夠經過設置upsert=true,這樣一旦匹配不到任何的數據時,會將當前的數據當成新的數據插入到collection當中

##移除數據 移除一樣提供了兩個方法一個是delete_one()另外一個並是delete_many()。

  • delete_one 一次只刪除一條記錄
  • delete_many() 能夠刪除多條匹配的記錄

###移除全部匹配的內容 下面的操做是刪除全部borough爲Manhattan

result = db.restaurants.delete_many({"borough": "Manhattan"})

上面的操做返回的是一個 DeleteResult 的對象,該對象記錄的是匹配的數量和刪除的數量

result.deleted_count 輸出的結果爲1263行,表示刪除的總數

移除全部的內容

result = db.restaurants.delete_many({})

上面不帶任何條件的執行的結果,刪除全部的內容 經過打印result.deleted_count結果爲15100,表示刪除了15100行記錄

###刪除Collection 下面的語句直接將restaurants這個集合刪除

db.restaurants.drop()

##數據集合 在mongodb當中 經過aggregate()進行分組

db.collection.aggregate([<stage1>, <stage2>, ...])

###經過字段進行分組,而且計算該字段的總數

咱們使用$group來指定指定的鍵(key)進行分組。在$group當中主要經過_id字段來進行分組。經過$group來訪問field路徑。在使用$前綴的字段名稱來進行訪問.

經過accumulators來計算每一組的數據數。下面的示例就是經過borough字段來進行分組,而且使用$sum來進行分組的 總數的累加

cursor = db.restaurants.aggregate(
    [
        {"$group": {"_id": "$borough", "count": {"$sum": 1}}}
    ]
)
for document in cursor:
	print(document)

上面的代碼執行以後的結果以下面所示

{'_id': None, 'count': 1}

{'_id': 'Missing', 'count': 51}

{'_id': 'Staten Island', 'count': 969}

{'_id': 'Queens', 'count': 5656}

{'_id': 'Bronx', 'count': 2338}

{'_id': 'Brooklyn', 'count': 6086}

過程分組集合

咱們使用$match篩選相應的集合。$match使用的是mongodb 查詢語法。 下面的示例是經過$match進行過濾,只有同時知足borough爲Queens和curisine爲Brazilian的條件纔會參與分組。 address.zipcodewdt 作爲分組的字段,而且$sum進行最終的累加彙總

cursor = db.restaurants.aggregate(
    [
        {"$match": {"borough": "Queens", "cuisine": "Brazilian"}},
        {"$group": {"_id": "$address.zipcode", "count": {"$sum": 1}}}
    ]
)

最終的結果以下所示

{'count': 1, '_id': '11377'}

{'count': 1, '_id': '11368'}

{'count': 2, '_id': '11101'}

{'count': 3, '_id': '11106'}

{'count': 1, '_id': '11103'}

相關文章
相關標籤/搜索