#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Author : CZW
# @Contact : czw011122@163.com
import pymongo
MONGO_DB = "mongodb://localhost:27017/?authSource=test"
class SaveData:
def __init__(self):
# 连接mongo
self.__mongo_conn = pymongo.MongoClient(MONGO_DB) # 连接mongo
mongo_conn_db = self.__mongo_conn.TEST
self.mongo_famous = mongo_conn_db["famous"]
def __del__(self):
self.__mongo_conn.close()
def insert_one_mongo(self, mongo_name, item, note=""):
"""
:param mongo_name:库名
:param item: 数据
:param note: 数据说明
:return:
"""
try:
mongo_name.insert_one(dict(item))
print(note, item)
return True
except Exception as e:
print("mongo_{}_{}_{}".format(note, item["_id"], self.error(str(e))))
def update_one_mongo(self, mongo_name, id, item, note="", upsert=True):
"""
:param mongo_name:库名
:param id:数据id
:param item: 数据
:param note: 数据说明
:param upsert: True如果数据找到了则修改数据,如果找不到就当做新数据插入,False如果数据找到了则修改数据,如果找不到就不管
:return:
"""
try:
mongo_name.update_one({"_id": id}, {"$set": item}, upsert=upsert)
return True
except Exception as e:
print("mongo_{}_{}_{}".format(note, id, self.error(str(e))))
def error(self, e):
if e.find("E11000 duplicate key error") != -1:
return "插入失败,id已存在"
elif e.find("document must be an instance of dict") != -1:
return "文档必须是dict"
elif e.find("field '_id' was found to have been altered to _id:") != -1:
return "修改id出错,id不可修改!"
elif e.find("update only works with $ operators") != -1:
return "只适用于$操作符"
else:
return e
if __name__ == '__main__':
s = SaveData()
# 插入数据
# s.insert_one_mongo(s.mongo_famous, item={"_id": 1, "name": "卢本伟"}, note="名人表插入")
# s.insert_one_mongo(s.mongo_famous, item={"_id": 2, "name": "蔡徐坤"}, note="名人表插入")
# s.insert_one_mongo(s.mongo_famous, item={"_id": 3, "name": "秦牛正威"}, note="名人表插入")
# 修改数据
# s.update_one_mongo(s.mongo_famous,id=1,item={"name":"阿巴阿巴","sex":1},note="名人表修改",upsert=False)
# s.update_one_mongo(s.mongo_famous,id=6,item={"name":"李小明同学","sex":1},note="名人表修改",upsert=True)
pymongo-基本操作2-插入与更新demo
最新推荐文章于 2024-06-21 08:06:06 发布