Python Data Science 简明教程

Python - NoSQL Databases

随着越来越多的数据变得非结构化或半结构化,通过 NoSql 数据库管理它们的需求不断增加。Python 也可以与 NoSQL 数据库交互,其方式类似于与关系数据库交互的方式。在本章中,我们将使用 python 与 MongoDB 交互,使其成为 NoSQL 数据库。如果您不了解 MongoDB,您可以在我们的教程 here. 中学习它

为了连接到 MongoDB,python 使用一个称为 pymongo 的库。使用 Anaconda 环境中的以下命令,您可以将此库添加到您的 python 环境中。

conda install pymongo

此库允许 python 使用 db 客户端连接到 MOngoDB。连接后,我们选择要用于各种操作的 db 名称。

Inserting Data

要将数据插入 MongoDB,我们使用 insert() 方法,该方法在数据库环境中可用。首先,我们使用下面所示的 python 代码连接到 db,然后提供一系列键值对形式的文档详细信息。

# 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')}

Updating Data

更新现有 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')}

Deleting Data

删除记录也很简单,可以使用 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

因此,我们看到 db 中不再存在特定记录了。