Linux 拨号vps windows公众号手机端

python如何连接mongodb

lewis 7年前 (2018-09-18) 阅读数 13 #VPS/云服务器
文章标签 mongodb

python连接mongodb的方法:在python中可以使用pymongo模块连接mongodb数据库,首先需要建立一个shell脚本文件,使用“from pymongo import MongoClient”指令导入pymongo模块,然后使用“client = MongoClient('localhost',27017)”指令建立mongodb数据库连接即可。

具体内容如下:

#使用pymongo模块连接mongoDB数据库

#coding=utf-8

frompymongoimportMongoClient

#建立MongoDB数据库连接

client=MongoClient('localhost',27017)

#连接所需数据库,test为数据库名

db=client.test

#连接所用集合,也就是我们通常所说的表,test为表名

collection=db.test

#接下里就可以用collection来完成对数据库表的一些操作

#查找集合中所有数据

foritemincollection.find():

printitem

#查找集合中单条数据

printcollection.find_one()

#向集合中插入数据

collection.insert({name:'Tom',age:25,addr:'Cleveland'})

#更新集合中的数据,第一个大括号里为更新条件,第二个大括号为更新之后的内容

collection.update({Name:'Tom'},{Name:'Tom',age:18})

#删除集合collection中的所有数据

collection.remove()

#删除集合collection

collection.drop()

版权声明

本文仅代表作者观点,不代表米安网络立场。

发表评论:

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

热门