使用PyMongo基本流程包括以下步骤:
1.连接MongoDB数据库:使用MongoClient类中的connect()函数或MongoClient()函数创建一个MongoDB数据库连接对象。
2.选择数据库和集合:使用MongoDB连接对象的xxx[“xxx”]操作来选择要进行操作的数据库和集合.
3.读取、写入或更新数据:使用PyMongo提供的API方法,例如insert_one()、insert_many()、find()、update_one()、update_many()等来对数据进行读取、写入和更新等操作。
4.删除数据:使用API方法delete_one()或delete_many()方法来删除单个或多个数据。
下面是一个使用PyMongo连接MongoDB,插入数据,并且查询数据的示例:
from pymongo import MongoClient
# 创建MongoDB客户端连接对象
client = MongoClient('mongodb://localhost:27017/')
# 选择要操作的数据库和集合
db = client['testdb'] # 选择数据库
collection = db['testcollection'] # 选择集合
# 插入数据
post = {'title': 'Python', 'author': 'Tom', 'content': 'Hello, MongoDB!', 'date': '2021-08-01'}
collection.insert_one(post)
# 查询数据
result = collection.find({'author': 'Tom'})
for item in result:
print(item)
首先,使用MongoClient类中的connect()函数或MongoClient()函数可以创建一个MongoDB数据库连接对象。然后,使用MongoDB连接对象的xxx[“xxx”]操作来选择要操作的数据库和集合。
接下来,使用insert_one()方法插入数据。注意,这里的post字典就是一个MongoDB的文档对象。
最后,使用find()方法查询数据,返回一个Cursor对象。使用for循环遍历Cursor对象,获取查询结果。
运行输出:
{'_id': ObjectId('61065adf3abb4fb38d1efb0b'), 'title': 'Python', 'author': 'Tom', 'content': 'Hello, MongoDB!', 'date': '2021-08-01'}
可以看到,查询结果返回了刚才插入的数据文档。这就是PyMongo的基本使用流程。