python3链接mongodb需要安装包,使用pip安装。
import pymongo
client = pymongo.MongoClient()
mydb = client['new_163']
mycol = mydb['items']
data = mycol.find()
print(data)
for i in data:
print(i['_id'])
看案例
import pymongo
client = pymongo.MongoClient()#链接
my_db = client['hwj']#创建数据库
my_col = my_db['stu']#创建集合
my_col.insert_many([
{'_id':1,'name':'hwj1','age':181},
{'_id':2,'name':'hwj2','age':182},
{'_id':3,'name':'hwj3','age':183}
])#插入数据
data = my_col.find({})#查看数据find--查看所有(循环输出数据),find_one--查看一条(不需要循环)
print(data)
for i in data:
print(i)
my_col.update_one(
{'name':'hwj1'},
{'$set':
{'name':'hwj11'}
}
)#修改update()--修改多条,update_one()--修改一条
my_col.remove()#删除
import pymongo
class classMongo(object):
'''
初始化mongo
'''
def __init__(self,db,collection):
self.client = pymongo.MongoClient()
self.db = self.client[db]
self.collection = self.db[collection]
'''
查询
'''
def mFind(self,where=False):
if where!=False:
data = self.collection.find({where})
else:
data = self.collection.find()
return data
def mFindOns(self,where=False):
if where!=False:
data = self.collection.find_one({where})
else:
data = self.collection.find_one()
return data
'''
插入
'''
def mInsert(self,data,only_one=True):
if only_one:
bool = self.collection.insert_one(data)
else:
bool = self.collection.insert_many(data)
return bool
'''
移除
'''
def mRemove(self,where=True):
if where:
bool = self.collection.remove(where)
else:
bool = self.collection.remove()
return bool
'''
修改
'''
def mUpdate(self,where,only_one=True):
if only_one:
bool = self.collection.update_one(where)
else:
bool = self.collection.update(where)
return bool
m = classMongo('hwj','stu')