pymongo连接MongoDB系列一
2016-10-12 本文已影响717人
菩提老鹰
导语
pymongo 是目前用的相对普遍一个python用来连接MongoDB的库,是工作中各种基本需求都能满足
具体api可以参考 pymongo API
pymongo github
[个人博客地址] - [pymongo连接MongoDB系列一]
安装 MongoDB
为了测试pyMongo连接mongodb,首先当然需要在centos下安装mongo,详细参考 Centos下安装MongoDB
安装 pymongo
如果没有pip, 建议先安装,至于为啥要用pip你懂得
yum install python-pip
pip 安装 pymongo
pip install pymongo
查看 pymongo是否安装成功
root@pts/4 $ python
Python 2.7.5 (default, Nov 20 2015, 02:00:19)
[GCC 4.8.5 20150623 (Red Hat 4.8.5-4)] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import pymongo
>>> pymongo.version
'3.2.2'
使用 pymongo
连接到 MongoDB
有两种方式,等同
>>> client = pymongo.MongoClient('192.168.100.3', 27017)
>>> print client
MongoClient(host=['192.168.100.3:27017'], document_class=dict, tz_aware=False, connect=True)
>>> client2 = pymongo.MongoClient('mongodb://192.168.100.3:27017/')
>>> print client2
MongoClient(host=['192.168.100.3:27017'], document_class=dict, tz_aware=False, connect=True)
>>>
得到 db 和 collection
有时候在脚本中会把 db 和 collection 作为参数使用,可以参考第二种方式
直接链接
>>> db = client.report
>>> print db
Database(MongoClient(host=['192.168.100.3:27017'], document_class=dict, tz_aware=False, connect=True), u'report')
>>> collection = db.source_register
>>> print collection
Collection(Database(MongoClient(host=['192.168.100.3:27017'], document_class=dict, tz_aware=False, connect=True), u'report'), u'source_register')
>>>
参数链接, 这种形式又有两种方法
## 定义参数
>>> pramadb = 'report'
>>> pramacoll = 'source_register'
## get db
>>> db2 = client[pramadb]
>>> db3 = client.get_database(pramadb)
>>> print db2
Database(MongoClient(host=['192.168.100.3:27017'], document_class=dict, tz_aware=False, connect=True), u'report')
>>> print db3
Database(MongoClient(host=['192.168.100.3:27017'], document_class=dict, tz_aware=False, connect=True), u'report')
>>>
## get collection
>>> coll2 = db2[pramacoll]
>>> coll3 = db3.get_collection(pramacoll)
>>> print coll2
Collection(Database(MongoClient(host=['192.168.100.3:27017'], document_class=dict, tz_aware=False, connect=True), u'report'), u'source_register')
>>> print coll3
Collection(Database(MongoClient(host=['192.168.100.3:27017'], document_class=dict, tz_aware=False, connect=True), u'report'), u'source_register')
>>>
常规操作举例
## insert or save
>>> mydict = {"name":"James", "age": 28}
>>> collection.save(mydict)
ObjectId('57fdf212bcd34f48c4fce15a')
## find
>>> collection.find({"name":"James"})[0]
{u'age': 28, u'_id': ObjectId('57fdf212bcd34f48c4fce15a'), u'name': u'James'}
>>>
_ _ _ 未完待续... _ _ _