1. 创建一个MyPyMongo.py文件

2. 导包

1
from pymongo import MongoClient

3. 创建类

1
2
3
4
5
6
7
8
9
10
11
12
13
14
class MyMongo:
def __init__(self, database, collection, **mongo_kwargs): # database 数据库名 collection 集合名(表) **mongo_kwargs 端口号 地址
self.data = MongoClient(**mongo_kwargs) # 连接MongoDB
self.db = self.data[database] # 进入数据库
self.collection = self.db[collection] # 进入集合(表)

def find_one(self, key: dict) -> dict: # 按条件指定查询
return self.collection.find_one(key)

def find(self) -> object: # 查询集合所有数据
return self.db.find()

def insert(self, info: dict) -> None: # 插入数据
self.db.insert(info)

4. 调用

1
2
3
4
m = MyMongo('conn', 'cate_test_set', **{'host': '127.0.0.1', 'port': 27017})
print(m.find_one({'name':'Asia'}))
m.find()
m.insert({'name1':'li'})