Python - NoSQL 資料庫



隨著越來越多的資料以非結構化或半結構化的形式出現,透過 NoSQL 資料庫管理這些資料的需求日益增長。Python 可以像與關係型資料庫互動一樣,以類似的方式與 NoSQL 資料庫互動。本章將使用 Python 與 MongoDB(作為 NoSQL 資料庫)進行互動。如果您不熟悉 MongoDB,可以在我們的教程這裡學習。

為了連線到 MongoDB,Python 使用一個名為pymongo的庫。您可以使用 Anaconda 環境中的以下命令將此庫新增到您的 Python 環境中。

conda install pymongo

此庫使 Python 能夠使用資料庫客戶端連線到 MongoDB。連線後,我們選擇要用於各種操作的資料庫名稱。

插入資料

要將資料插入 MongoDB,我們使用資料庫環境中提供的 insert() 方法。首先,我們使用下面所示的 Python 程式碼連線到資料庫,然後我們以一系列鍵值對的形式提供文件詳細資訊。

# Import the python libraries
from pymongo import MongoClient
from pprint import pprint

# Choose the appropriate client
client = MongoClient()

# Connect to the test db 
db=client.test

# Use the employee collection
employee = db.employee
employee_details = {
    'Name': 'Raj Kumar',
    'Address': 'Sears Streer, NZ',
    'Age': '42'
}

# Use the insert method
result = employee.insert_one(employee_details)

# Query for the inserted document.
Queryresult = employee.find_one({'Age': '42'})
pprint(Queryresult)

執行上述程式碼後,將產生以下結果。

{u'Address': u'Sears Streer, NZ',
 u'Age': u'42',
 u'Name': u'Raj Kumar',
 u'_id': ObjectId('5adc5a9f84e7cd3940399f93')}

更新資料

更新現有的 MongoDB 資料類似於插入資料。我們使用 MongoDB 自帶的 update() 方法。在下面的程式碼中,我們用新的鍵值對替換現有記錄。請注意我們如何使用條件標準來決定要更新哪個記錄。

# Import the python libraries
from pymongo import MongoClient
from pprint import pprint

# Choose the appropriate client
client = MongoClient()

# Connect to db
db=client.test
employee = db.employee

# Use the condition to choose the record
# and use the update method
db.employee.update_one(
        {"Age":'42'},
        {
        "$set": {
            "Name":"Srinidhi",
            "Age":'35',
            "Address":"New Omsk, WC"
        }
        }
    )

Queryresult = employee.find_one({'Age':'35'})

pprint(Queryresult)

執行上述程式碼後,將產生以下結果。

{u'Address': u'New Omsk, WC',
 u'Age': u'35',
 u'Name': u'Srinidhi',
 u'_id': ObjectId('5adc5a9f84e7cd3940399f93')}

刪除資料

刪除記錄也很直接,我們使用 delete 方法。在這裡,我們也提到了用於選擇要刪除的記錄的條件。

# Import the python libraries
from pymongo import MongoClient
from pprint import pprint

# Choose the appropriate client
client = MongoClient()

# Connect to db
db=client.test
employee = db.employee

# Use the condition to choose the record
# and use the delete method
db.employee.delete_one({"Age":'35'})

Queryresult = employee.find_one({'Age':'35'})

pprint(Queryresult)

執行上述程式碼後,將產生以下結果。

None

因此,我們看到該特定記錄不再存在於資料庫中。

廣告
© . All rights reserved.