# coding=utf-8
# 使用pymongo模块连接mongoDB数据库
from pymongo import MongoClient
# 建立MongoDB数据库连接
client = MongoClient('localhost', 27017)
# 连接所需数据库,test为数据库名
db = client.xiaomei#第二种写法 db = client['xiaomei']
# 连接所用集合,也就是我们通常所说的表,test为表名
collection = db.test#第二种写法 col = db['test_set']
# 接下里就可以用collection来完成对数据库表的一些操作
#向集合中插入一条数据
collection.insert({"name":'newfroend',"age":25,"addr":'Cleveland'})
#向集合中插入多条数据
collection.insert([{"name":'lucy',"age":25,"addr":'Cleveland'},{"name":'pisa',"age":18,"addr":'Idin'}])
#更新集合中的数据,第一个大括号里为更新条件,第二个大括号为更新之后的内容
collection.update({"name":'newfroend'},{"Name":'oldfriend',"age":18})
# 删除数据一条
collection.delete_one({"name":'lucy'})
# 删除数据多条
collection.delete_many({"name":'lucy'})
#查找集合中单条数据
print(collection.find_one())
# 查找集合中所有数据
for item in collection.find():
print(item)
#删除集合collection中的所有数据
collection.remove()
#删除集合collection
collection.drop()
Python操作mongodb增删改查
猜你喜欢
转载自blog.csdn.net/weixin_44517681/article/details/102843532
今日推荐
周排行