iis服务器助手广告广告
返回顶部
首页 > 资讯 > 后端开发 > Python >Python连接MongoDB数据库并执
  • 574
分享到

Python连接MongoDB数据库并执

数据库PythonMongoDB 2023-01-31 05:01:17 574人浏览 独家记忆

Python 官方文档:入门教程 => 点击学习

摘要

环境设置:[root@mongoDB ~]# cat /etc/redhat-release  Centos release 6.9 (Final) [root@monGodb ~]# python -V Python 2.6.61.首先确


环境设置:

[root@mongoDB ~]# cat /etc/redhat-release 
Centos release 6.9 (Final)
[root@monGodb ~]# python -V
Python 2.6.6


1.首先确保,Mongodb数据库运行

捕获.PNG


2.安装pymongo模块

官网:https://pypi.python.org/pypi/pymongo/(按需下载)

[root@mongodb src]# wget Https://pypi.python.org/packages/a3/fe/826348375bfe2d11c96cdc7b7cbabbd84b8b15b62eb33638ee3241fca5f9/pymongo-3.6.1.tar.gz#md5=0d72c87fb93cea0759529befafefce54
[root@mongodb src]# tar -zxvf pymongo-3.6.1.tar.gz 
[root@mongodb src]# cd pymongo-3.6.1
[root@mongodb pymongo-3.6.1]# python setup.py  install


3.开始编写python脚本,连接Mongodb数据库

[root@mongodb ~]# cat mongodb.py 

#!/usr/bin/env python
#-*- coding: UTF-8 -*-
#导入模块
from pymongo import MongoClient
#建立Mongodb数据库连接
client=MongoClient('localhost',27017)
#test为数据库
db=client.test
#test为集合,相当于表名
collection=db.test
#插入集合数据
collection.insert({"title":"test"})
#打印集合中所有数据
for item in collection.find():
    print item
#更新集合里的数据
collection.update({"title":"test"},{"title":"this is update test"})
#关闭连接
client.close()
#!!!!其他操作
#查找集合中单条数据
#print collection.find_one()
#删除集合collection中的所有数据
#collection.remove()
#删除集合collection
#collection.drop()


4.执行脚本,进库查询是否更新集合数据

捕获.PNG


[root@mongodb ~]# /opt/mongodb/bin/mongo

MongoDB shell version v3.4.5
connecting to: mongodb://127.0.0.1:27017
MongoDB server version: 3.4.5
> use test
switched to db test
> db.test.find()
{ "_id" : ObjectId("5ab174b2685a5f0b11f67b4f"), "title" : "this is update test" }
>  #更新成功



Python连接MongoDB 成功!!!!








--结束END--

本文标题: Python连接MongoDB数据库并执

本文链接: https://www.lsjlt.com/news/189114.html(转载时请注明来源链接)

有问题或投稿请发送至: 邮箱/279061341@qq.com    QQ/279061341

本篇文章演示代码以及资料文档资料下载

下载Word文档到电脑,方便收藏和打印~

下载Word文档
软考高级职称资格查询
编程网,编程工程师的家园,是目前国内优秀的开源技术社区之一,形成了由开源软件库、代码分享、资讯、协作翻译、讨论区和博客等几大频道内容,为IT开发者提供了一个发现、使用、并交流开源技术的平台。
  • 官方手机版

  • 微信公众号

  • 商务合作