前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >Python之NoSQL数据库增删改查

Python之NoSQL数据库增删改查

作者头像
菲宇
发布2022-12-02 14:23:14
5800
发布2022-12-02 14:23:14
举报
文章被收录于专栏:菲宇菲宇菲宇

使用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中。

本文参与 腾讯云自媒体分享计划,分享自作者个人站点/博客。
原始发表:2017-07-25,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • 插入数据
  • 更新数据
  • 删除数据
相关产品与服务
云数据库 MongoDB
腾讯云数据库 MongoDB(TencentDB for MongoDB)是腾讯云基于全球广受欢迎的 MongoDB 打造的高性能 NoSQL 数据库,100%完全兼容 MongoDB 协议,支持跨文档事务,提供稳定丰富的监控管理,弹性可扩展、自动容灾,适用于文档型数据库场景,您无需自建灾备体系及控制管理系统。
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档