随着越来越多的数据变为非结构化或半结构化数据,通过NoSql数据库管理数据的需求增加了,Python还可以与关系数据库类似的方式与NoSQL数据库进行交互,在本章中,无涯教程将使用python与MongoDB作为NoSQL数据库进行交互。
为了连接到MongoDB,python使用称为 pymongo 的库,您可以使用Anaconda环境中的以下命令将此库添加到python环境中。
conda install pymongo
该库使python可以使用db客户端连接到MongoDB,连接后,选择要用于各种操作的数据库名称。
要将数据插入MongoDB,无涯教程使用在数据库环境中可用的insert()方法。
# Import the python libraries from pymongo import MongoClient from pprint import pprint # Choose the appropriate client client = MongoClient() # 连接到测试数据库 db=client.test # 使用 employee 员工集合 employee = db.employee employee_details = { 'Name': 'Raj Kumar', 'Address': 'Sears Streer, NZ', 'Age': '42' } # 使用插入方法 result = employee.insert_one(employee_details) # 查询插入的数据。 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() # 连接到数据库 db=client.test employee = db.employee # 使用条件选择记录并使用更新方法 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() # 连接到数据库 db=client.test employee = db.employee # 使用条件选择记录并使用delete删除方法 db.employee.delete_one({"Age":'35'}) Queryresult = employee.find_one({'Age':'35'}) pprint(Queryresult)
当执行上面的代码时,它将产生以下输出。
None
因此,无涯教程看到该特定记录不再存在于db中。
祝学习愉快!(内容编辑有误?请选中要编辑内容 -> 右键 -> 修改 -> 提交!)
Python实战 · 从0到1搭建直播视频平台 -〔Barry〕