import pymongo, math
mongo_url = 'mongodb://127.0.0.1'
# 链接数据库
client = pymongo.MongoClient(mongo_url)
class mongo(object):
def __init__(self, dn_name):
# 需要打开的数据库
self.db = client[dn_name]
# 查询数据库的所有集合
self.collist = self.db.list_collection_names()
# 插入文档
def insert_one(self, col_name, data):
# 打开集合
col = self.db[col_name]
return col.insert_one(data)
# 插入多个文档
def insert_many(self, col_name, list):
# 打开集合
col = self.db[col_name]
return col.insert_many(list)
# 查询一条数据
def find_one(self, col_name, where={}):
# 打开集合
col = self.db[col_name]
return col.find_one(where)
# 查询多条数据
def find(self, col_name, where={}, sort=[(date, -1)], select={_id: 0, __v: 0}):
# 打开集合
col = self.db[col_name]
return col.find(where, select).sort(sort)
# 查询集合的条数
def count(self, col_name, where={}):
# 打开集合
col = self.db[col_name]
return col.find(where).count()
# 分页查询
def find_page(self, col_name, where={}, page=1, sort=[(date, -1)], page_num=20, select={_id: 0, __v: 0}):
# 打开集合
col = self.db[col_name]
# 数据总条数
counts = col.find(where).count()
# 总页数
all_page = math.abs(counts / page_num)
# 数据偏移量
if page < all_page:
skip = (page - 1) * page_num
else:
skip = all_page * page_num
# 查询总条数
list = col.find(where, select).sort(sort).limit(page_num).skip(skip)
return {"cur_page": page, "counts": counts, "list": list, "all_page": all_page}
# 更新一条数据
def update_one(self,col_name,where,update):
# 打开集合
col = self.db[col_name]
return col.update_one(where,update)
# 更新多条数据
def update_many(self,col_name,where,update):
# 打开集合
col = self.db[col_name]
return col.update_many(where, update)
# 删除一条数据
def delete_one(self,col_name,where):
# 打开集合
col = self.db[col_name]
return col.delete_one(where)
# 删除多条数据
def delete_many(self,col_name,where):
# 打开集合
col = self.db[col_name]
return col.delete_many(where)
转载请注明原文地址:https://ipadbbs.8miu.com/read-29535.html