Python存连接MongoDB

step1:安装pymongo库
pip install pymongo
step2:使用pymongo模块连接mongoDB数据库
#coding=utf-8
from pymongo import MongoClient

#建立MongoDB数据库连接
client = MongoClient('localhost',27017)

#连接所需数据库,testdb为数据库名(没有则新建)
db=client.testdb

#连接所用集合,也就是我们通常所说的表,test为表名(没有则新建)
collection=db.test

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

#查找集合中所有数据,返回列表
for item in collection.find():
    print(item)

#查找集合中单条数据
print collection.find_one() 

#向集合中插入数据
collection.insert({name:'Tom',age:25,addr:'Cleveland'})


#更新集合中的数据,第一个大括号里为更新条件,第二个大括号为更新之后的内容
collection.update({Name:'Tom'},{Name:'Tom',age:18})

#删除name=panghu的全部记录
my_set.remove({'name': 'panghu'})

#删除name=lisi的某个id的记录(按照id删除数据)
id = my_set.find_one({"name":"zhangsan"})["_id"]
my_set.remove(id)

#删除集合collection中的所有数据
collection.remove()

#删除集合collection
collection.drop()

猜你喜欢

转载自blog.csdn.net/DylanYuan/article/details/81746223