目录

Python NoSQL 数据库 Databases

随着越来越多的数据变为非结构化或半结构化,通过NoSql数据库管理它们的需求也在增加。 Python也可以与与Relational数据库交互的方式类似地与NoSQL数据库交互。 在本章中,我们将使用python与MongoDB作为NoSQL数据库进行交互。 如果您是MongoDB的新手,可以在我们的教程中学习它here.

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

conda install pymongo

该库使python能够使用db客户端连接到MOngoDB。 连接后,我们选择要用于各种操作的数据库名称。

插入数据

要将数据插入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')}

更新数据

更新现有的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

所以我们看到db中不存在特定记录了。

↑回到顶部↑
WIKI教程 @2018