背景
最近项目中用到了mongodb,并且用python 的pymongo包操作。本文就把目前遇到的问题和学习经历做个小结,方便日后查询。
Mongodb启动
- 安装mongodb
https://www.mongodb.com/download-center#community
- 配置环境变量
把mongodb安装路径下的bin文件路径加入系统环境变量,我这里路径是 D:\MongoDB\bin
- 设置数据存放的根目录。开启命令行窗口(开始—>运行—>cmd),输入命令
mongod --dbpath D:\Mongodb\data
看到如下信息就OK了
mongodb默认的端口号27017。我们也可以在配置时指定端口。例:如果我们想指定mongodb的服务端口号为10001,命令如下:
mongod --dbpath D:\Mongodb\data --port 10001
在浏览器输入: http://localhost:27017 可以看到如下提示:
It looks like you are trying to access MongoDB over HTTP on the native driver port.
此时,Mongodb数据库服务已经完全启动了。
此部分参考:http://chenzhou123520.iteye.com/blog/1582174
Robomongo 使用基本使用
- 安装mongodb的客户端管理工具robomongo。并创建一个名为test的新连接。
下载地址:https://robomongo.org/
- 新建数据库
右键连接名—> create DataBase。新建一个名为“xyd”的数据库,下文会用到。
- 新建表
右键Collections —> create Collection。这里一个Collection相对于关系型数据库中的表概念。新建一张“mytest”的表,下文会用到。
Robomongo 快捷键
Ctrl+R 刷新界面
Ctrl+T 打开新的命令窗口
Ctrl+Enter 运行命令
Mongo命令
关于插入和查询命令,以下网站做了不错的总结,这里就不重复造轮子了。
http://www.cnblogs.com/stephen-liu74/archive/2012/08/03/2553803.html
http://www.cnblogs.com/viviman/archive/2012/11/21/2780562.html
http://www.runoob.com/mongodb/mongodb-insert.html
Pymongo 使用
pymongo是python操作 mongodb的工具包。不做概念性的介绍了,以下为直接操作。
pymongo 安装
- 安装python,设置好环境变量
- 安装python包管理工具pip
- 用pip安装pymongo
项目主页:http://api.mongodb.com/python/current/installation.html
安装命令:
python -m pip install pymongo
之前使用过的话,就升级pymongo:
python -m pip install --upgrade pymongo
我之前安装过,在此就升级了包。结果如下图:3.0.1升级到3.3.0,
pymongo 测试
import pymongo
import sys
import traceback
MONGODB_COnFIG= {
'host': '127.0.0.1',
'port': 27017,
'db_name': 'xyd',
'username': None,
'password': None
}
class MongoConn(object):
def __init__(self):
try:
self.cOnn= pymongo.MongoClient(MONGODB_CONFIG['host'], MONGODB_CONFIG['port'])
self.db = self.conn[MONGODB_CONFIG['db_name']]
self.username=MONGODB_CONFIG['username']
self.password=MONGODB_CONFIG['password']
if self.username and self.password:
self.cOnnected= self.db.authenticate(self.username, self.password)
else:
self.cOnnected= True
except Exception:
print traceback.format_exc()
print 'Connect Statics Database Fail.'
sys.exit(1)
from myconn import MongoConn
if __name__ == "__main__":
my_cOnn= MongoConn()
datas = [
{'_id':1, 'data':12},
{'_id':2, 'data':22},
{'_id':3, 'data':'cc'}
]
my_conn.db['mytest'].insert(datas)
res=my_conn.db['mytest'].find({})
for k in res:
print k
Python控制台返回结果:
Mongodb中结果:
以上表示测试成功
pymongo 操作
- 工程中的连接类:和上文的连接类最大的不同是设置单例模式。
不做介绍,可参考:http://ghostfromheaven.iteye.com/blog/1562618
import pymongo
import sys
import traceback
MONGODB_COnFIG= {
'host': '127.0.0.1',
'port': 27017,
'db_name': 'xyd',
'username': None,
'password': None
}
class Singleton(object):
def __new__(cls, *args, **kwargs):
if not hasattr(cls, '_instance'):
orig = super(Singleton, cls)
cls._instance = orig.__new__(cls, *args, **kwargs)
return cls._instance
class MongoConn(Singleton):
def __init__(self):
try:
self.cOnn= pymongo.MongoClient(MONGODB_CONFIG['host'], MONGODB_CONFIG['port'])
self.db = self.conn[MONGODB_CONFIG['db_name']]
self.username=MONGODB_CONFIG['username']
self.password=MONGODB_CONFIG['password']
if self.username and self.password:
self.cOnnected= self.db.authenticate(self.username, self.password)
else:
self.cOnnected= True
except Exception:
print traceback.format_exc()
print 'Connect Statics Database Fail.'
sys.exit(1)
from myconn import MongoConn
import traceback
def check_connected(conn):
if not conn.connected:
raise NameError, 'stat:connected Error'
def save(table, value):
try:
my_cOnn= MongoConn()
check_connected(my_conn)
my_conn.db[table].save(value)
except Exception:
print traceback.format_exc()
def insert(table, value):
try:
my_cOnn= MongoConn()
check_connected(my_conn)
my_conn.db[table].insert(value, continue_on_error=True)
except Exception:
print traceback.format_exc()
def update(table, conditions, value, s_upsert=False, s_multi=False):
try:
my_cOnn= MongoConn()
check_connected(my_conn)
my_conn.db[table].update(conditions, value, upsert=s_upsert, multi=s_multi)
except Exception:
print traceback.format_exc()
def upsert_mary(table, datas):
try:
my_cOnn= MongoConn()
check_connected(my_conn)
bulk = my_conn.db[table].initialize_ordered_bulk_op()
for data in datas:
_id=data['_id']
bulk.find({'_id': _id}).upsert().update({'$set': data})
bulk.execute()
except Exception:
print traceback.format_exc()
def upsert_one(table, data):
try:
my_cOnn= MongoConn()
check_connected(my_conn)
query = {'_id': data.get('_id','')}
if not my_conn.db[table].find_one(query):
my_conn.db[table].insert(data)
else:
data.pop('_id')
my_conn.db[table].update(query, {'$set': data})
except Exception:
print traceback.format_exc()
def find_one(table, value):
try:
my_cOnn= MongoConn()
check_connected(my_conn)
return my_conn.db[table].find_one(value)
except Exception:
print traceback.format_exc()
def find(table, value):
try:
my_cOnn= MongoConn()
check_connected(my_conn)
return my_conn.db[table].find(value)
except Exception:
print traceback.format_exc()
def select_colum(table, value, colum):
try:
my_cOnn= MongoConn()
check_connected(my_conn)
return my_conn.db[table].find(value, {colum:1})
except Exception:
print traceback.format_exc()
if __name__ == "__main__":
file_path = './enterprise_all.txt'
company_list = []
with open(file_path, "r") as in_file:
for line in in_file:
dic={}
dic['_id']=line.strip()
dic['name']=line.strip()
company_list.append(dic)
upsert_mary('mytest',company_list)
datas = [
{'_id':8, 'data':88},
{'_id':9, 'data':99},
{'_id':36, 'data':3366}
]
insert('mytest', datas)
data={'_id':6, 'data':66}
save('mytest',data)
update('mytest',{'_id':8},{'$set':{'data':'888'}}, False, False)
data={'_id':36, 'data':'dsd'}
upsert_one('mytest',data)
res=select_colum('mytest',{},'_id')
for k in res:
for key, value in k.iteritems():
print key,":",value
res=find('mytest',{})
for k in res:
for key, value in k.iteritems():
print key,":",value,
print
res=find_one('mytest',{})
for k in res:
print k,':',res[k]