Python 连接MongoDB数据库手札(PyMongo)
2016-07-10 14:51
465 查看
1 PyMango 安装
如果还不知道怎么安装MongoDB可以先看这里,包括如何启动相应的服务Ubuntu の MongoDB 安装教程及简单操作
要想在Python中使用MongoDB,需要安装PyMongo,通过PyMongo 我们在Python中就可以链接MongoDB数据库了,这里我是使用了Pip来安装的,如果还没清楚Pip怎么安装的可以看看之前的博文
pip install pymongo
完成了这条指令之后,我们就可以在Python当中进行数据库的连接操作了。
2 Python链接代码
在这里我直接给出一个示例了,注意的是,Pymango可以直接把Python中dict类型的数据直接存入,也可以直接取出,是不是很方便?#encoding:utf=8 import pymongo as pm import json class MongoOperator: def __init__(self, host, port, db_name, default_collection): ''' 设置mongodb的地址,端口以及默认访问的集合,后续访问中如果不指定collection,则访问这个默认的 :param host: 地址 :param port: 端口 :param db_name: 数据库名字 :param default_collection: 默认的集合 ''' #建立数据库连接 self.client = pm.MongoClient(host=host, port=port) #选择相应的数据库名称 self.db = self.client.get_database(db_name) #设置默认的集合 self.collection = self.db.get_collection(default_collection) def insert(self, item, collection_name =None): ''' 插入数据,这里的数据可以是一个,也可以是多个 :param item: 需要插入的数据 :param collection_name: 可选,需要访问哪个集合 :return: ''' if collection_name != None: collection = self.db.get_collection(self.db) collection.insert(item) else: self.collection.insert(item) def find(self, expression =None, collection_name=None): ''' 进行简单查询,可以指定条件和集合 :param expression: 查询条件,可以为空 :param collection_name: 集合名称 :return: 所有结果 ''' if collection_name != None: collection = self.db.get_collection(self.db) if expression == None: return collection.find() else: return collection.find(expression) else: if expression == None: return self.collection.find() else: return self.collection.find(expression) def get_collection(self, collection_name=None): ''' 很多时候单纯的查询不能够通过这个类封装的方法执行,这时候就可以直接获取到对应的collection进行操作 :param collection_name: 集合名称 :return: collection ''' if collection_name == None: return self.collection else: return self.get_collection(collection_name) db = MongoOperator('10.0.0.39',27017,'test_db','test_collection') item = {} item['name'] = 'mebiuw' item['age'] = '23' db.insert(item) for item in db.find(): print(item)
3 其他
如果有其他我再补充,这篇主要是代码上的,上一篇主要是环境上的,遇到问题我会及时补充相关文章推荐
- 分享微信开发Html5轻游戏中的几个坑
- Android之获取手机上的图片和视频缩略图thumbnails
- Python动态类型的学习---引用的理解
- Python3写爬虫(四)多线程实现数据爬取
- 垃圾邮件过滤器 python简单实现
- 下载并遍历 names.txt 文件,输出长度最长的回文人名。
- 如何在 Fedora 上安装 MongoDB 服务器
- install and upgrade scrapy
- Scrapy的架构介绍
- Centos6 编译安装Python
- 使用Python生成Excel格式的图片
- 让Python文件也可以当bat文件运行
- [Python]推算数独
- PHP添加yaf xhprof mongodb 同理
- mongodb安装
- Python中zip()函数用法举例
- Python中map()函数浅析