Code前端首页关于Code前端联系我们

Python数据科学教程:作为NoSQL数据库与MongoDB对接

terry 2年前 (2023-09-25) 阅读数 47 #后端开发

越来越多的数据以非结构化或半结构化的方式提供,需要NoSql数据库来管理它们。 Python 可以以与关系数据库类似的方式与 NoSQL 数据库交互。在本章中,我们将使用 python 与作为 NoSQL 数据库的 MongoDB 进行交互。

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

conda install pymongo
Shell

该库允许 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)
Python

运行上面的示例代码,得到以下结果 -

{u'Address': u'Sears Streer, NZ',
 u'Age': u'42',
 u'Name': u'Raj Kumar',
 u'_id': ObjectId('5adc5a9f84e7cd3940399f93')}
Shell

更新数据

与插入现有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)
Python

执行上述代码时,会产生以下输出。

{u'Address': u'New Omsk, WC',
 u'Age': u'35',
 u'Name': u'Srinidhi',
 u'_id': ObjectId('5adc5a9f84e7cd3940399f93')}
Shell

删除数据

使用方法删除删除记录也很简单。此处还提到了用于选择要删除的文件的标准。

# 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)
Python

执行上面的示例代码,得到如下输出 -

None
Shell

所以你可以看到db中的特殊文件不再存在。。

版权声明

本文仅代表作者观点,不代表Code前端网立场。
本文系作者Code前端网发表,如需转载,请注明页面地址。

发表评论:

◎欢迎参与讨论,请在这里发表您的看法、交流您的观点。

热门