随着越来越多的数据以非结构化或半结构化的方式来提供,需要通过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
中。