pymongo的简单使用
测试项目
mongo_conf.py:
# -*- coding:utf-8 -*- from pymongo import MongoClient, ReadPreference MONGOS = { "ad_api_integration": { 'host': 'mongodb://10.0.0.32:27017/', # 自己的mongo装在哪里就使用哪里的地址 'connectTimeoutMS': 5000, 'tz_aware': True }, } _mongo_conns = dict() # 防止链接重复做的一个cache def gen_mongo_connection(conn_name): global _mongo_conns if conn_name in _mongo_conns: return _mongo_conns[conn_name] conn = MongoClient(**MONGOS[conn_name]) _mongo_conns[conn_name] = conn return _mongo_conns[conn_name] class MongoDBManager(object): def __init__(self, name, db_name, is_read_preference=True): self.client = gen_mongo_connection(name) self.db_name = db_name self.is_read_preference = is_read_preference def get_read(self, tb_name): if self.is_read_preference: return self.client.get_database( self.db_name, read_preference=ReadPreference.SECONDARY).get_collection(tb_name) else: return self.client.get_database( self.db_name).get_collection(tb_name) def get_write(self, tb_name): return self.client.get_database( self.db_name).get_collection(tb_name) class MongoDBIntegration(MongoDBManager): def __init__(self): super(MongoDBIntegration, self).__init__('ad_api_integration', 'whw_test', False) ### 基于模块导入的单例模式 db_mongo_integration = MongoDBIntegration()
test1.py
# -*- coding:utf-8 -*- from pprint import pprint from mongo_conf import db_mongo_integration mongo_conn = db_mongo_integration.get_write("mongo_test_table") ### insert操作 arg = { "_id":2, "name":"naruto", "info":{ "age":23, "score":90, "gender":"male", "interests":["螺旋丸","嘴遁"], } } # insert一个 ~~ 多个的话使用 insert_many方法 mongo_conn.insert_one(arg) ### 更新操作 update_arg = { "_id":2, "name":"naruto", "info":{ "age":25, "score":100, "gender":"male", "interests":["螺旋丸666","嘴遁666"], } } mongo_conn.update({"_id":2},update_arg) ### 删除table中的数据 # mongo_conn.remove({"_id":2}) # 删除table # mongo_conn.drop() ### 查看 ret = mongo_conn.find() print("ret>>>",ret) for item in ret: pprint(item) ### 查询这个table下的文档的数量 count = mongo_conn.count() print("count_total>>>",count) ### 查询这个table下 _id=2 的文档有几个 count = mongo_conn.count({"_id":2}) print("count_id=2>>>",count) ### 查询table下 id=2 的文档的具体信息 find_ret = mongo_conn.find({"_id":2}) print("find_ret>>>",find_ret)
可以封装一下insert与update的操作
def insert_or_update_mongo(key:str,modify_dic:dict,mongo_conn): # key 就是 id_ count_ = mongo_conn.count({"_id":key}) # insert if count_ == 0: modify_dic["_id"] = key mongo_conn.insert_one(modify_dic) # update if count_ > 0: mongo_conn.update({"_id":key},modify_dic)
终端查询命令
参考文章
https://python-web-guide.readthedocs.io/zh/latest/database/mongo.html