Python NoSQL資料庫


隨著越來越多的資料以非結構化或半結構化的方式來提供,需要通過NoSql資料庫來管理它們。 Python也可以以與關聯式資料庫互動的相似方式與NoSQL資料庫進行互動。 在本章中,我們將使用python作為NoSQL資料庫與MongoDB進行互動。 如果您是MongoDB的新手,可以通過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'})
print(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'})

print(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'})

print(Queryresult)

執行上面範例程式碼,得到以下結果 -

None

所以看到特定的記錄不再存在於db中。