#!/usr/bin/env python
# -*- coding:utf-8 -*-
from pymongo import MongoClient
settings = {
"ip": "172.28.xx.xxx", # ip
"port": 27117, # 端口
"db_name": "wangzs", # 数据库名字
"set_name": "books" # 集合名字
}
class Book():
def __init__(self, title, content):
self.title = title
self.content = content
def convert_to_dict(obj):
'''把Object对象转换成Dict对象'''
dict = {}
dict.update(obj.__dict__)
return dict
class MyMongoDB(object):
def __init__(self):
try:
self.conn = MongoClient(settings["ip"], settings["port"])
except Exception as e:
print(e)
self.db = self.conn[settings["db_name"]]
self.my_set = self.db[settings["set_name"]]
def insert(self, dic):
print("insert...")
self.my_set.insert(dic)
def update(self, dic, newdic):
print("update...")
self.my_set.update(dic, newdic)
def delete(self, dic):
print("delete...")
self.my_set.remove(dic)
def dbfind(self, dic={}):
print("find...")
data = self.my_set.find(dic)
for result in data:
print(result)
if __name__ == "__main__":
dic = {"name": "zhangsan", "age": 18}
mongo = MyMongoDB()
mongo.dbfind()
mongo.insert(dic)
mongo.dbfind({"name": "zhangsan"})
mongo.update({"name": "zhangsan"}, {"$set": {"age": "25"}})
mongo.dbfind({"name": "zhangsan"})
mongo.delete({"name": "zhangsan"})
mongo.dbfind({"name": "zhangsan"})
print("--插入对象--")
book = Book("python教程","入门的好书")
mongo.insert(convert_to_dict(book))
python mongodb操作
最新推荐文章于 2024-05-17 13:57:20 发布
本文通过一个具体的示例介绍了如何使用Python操作MongoDB数据库,包括连接数据库、插入数据、查找数据、更新数据以及删除数据等基本操作。示例中定义了一个书籍类并实现了将对象转换为字典的功能,便于进行数据库操作。
8万+

被折叠的 条评论
为什么被折叠?



