码迷,mamicode.com
首页 > 数据库 > 详细

pymongo连接MongoDB

时间:2017-11-25 17:22:40      阅读:212      评论:0      收藏:0      [点我收藏+]

标签:linu   col   nbsp   没有   drive   3.2   yum   block   more   

导语

pymongo 是目前用的相对普遍一个python用来连接MongoDB的库,是工作中各种基本需求都能满足
具体api可以参考

pymongo API
pymongo github

安装 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), ureport)
>>> collection = db.source_register
>>> print collection
Collection(Database(MongoClient(host=[192.168.100.3:27017], document_class=dict, tz_aware=False, connect=True), ureport), usource_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), ureport)
>>> print db3
Database(MongoClient(host=[192.168.100.3:27017], document_class=dict, tz_aware=False, connect=True), ureport)
>>> 

## 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), ureport), usource_register)
>>> print coll3
Collection(Database(MongoClient(host=[192.168.100.3:27017], document_class=dict, tz_aware=False, connect=True), ureport), usource_register)
>>>

 

常规操作举例

## insert or save 
>>> mydict = {"name":"James", "age": 28}
>>> collection.save(mydict)
ObjectId(57fdf212bcd34f48c4fce15a)

## find
>>> collection.find({"name":"James"})[0]
{uage: 28, u_id: ObjectId(57fdf212bcd34f48c4fce15a), uname: uJames}
>>>

 

pymongo连接MongoDB

标签:linu   col   nbsp   没有   drive   3.2   yum   block   more   

原文地址:http://www.cnblogs.com/zhouxinfei/p/7895515.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!