在 Python 中使用 PyMongo 处理 MongoDB 查询结果
- 安装 PyMongo
pip install pymongo
- 连接 MongoDB
from pymongo import MongoClient client = MongoClient('mongodb://localhost:27017/') db = client['mydatabase']
- 查询数据
collection = db['customers']
# 查询所有记录
results = collection.find()
# 查询指定记录
result = collection.find_one({'name': 'pidancode.com'})
- 遍历查询结果
collection = db['customers']
results = collection.find()
for result in results:
print(result)
- 插入数据
collection = db['customers']
data = {'name': 'pidancode.com', 'country': 'China'}
collection.insert_one(data)
- 更新数据
collection = db['customers']
collection.update_one({'name': 'pidancode.com'}, {'$set': {'country': 'USA'}})
- 删除数据
collection = db['customers']
collection.delete_one({'name': 'pidancode.com'})
相关文章