pymongo连接MongoDB

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了pymongo连接MongoDB相关的知识,希望对你有一定的参考价值。

导语

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是否安装成功

[email protected]/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的主要内容,如果未能解决你的问题,请参考以下文章

pymongo连接MongoDB

使用pymongo连接mongodb时报错:pymongo.errors.OperationFailure: not authorized

django mongodb 使用 djongo 和 pymongo 连接

pymongo使用方法

python—连接mongodb

pymongo使用方法