Python 使用pymongo操作mongodb库

1,安装python3.5

如果python还没有安装,可以直接用yum安装,

[python] view plain copy
 
  1. # 不过安装的是2.6 version  
  2. yum install -y python  

源码安装3.5

[python] view plain copy
 
  1. wget https://www.python.org/ftp/python/3.5.0/Python-3.5.0.tgz  
  2. tar -xvf Python-3.5.0.tgz  
  3. cd Python-3.5.0  
  4. ./configure --prefix=/usr/local--enable-shared  
  5. make  
  6. make install  
  7. ln -s /usr/local/bin/python3 /usr/bin/python3  



运行Python之前需要配置库

echo /usr/local/lib >> /etc/ld.so.conf.d/local.conf

ldconfig

运行演示

python3 --version

部分执行过程:

[python] view plain copy
 
  1. [root@03_sdwm Python-3.5.0]# echo/usr/local/lib >> /etc/ld.so.conf.d/local.conf  
  2. [root@03_sdwm Python-3.5.0]# ldconfig  
  3. [root@03_sdwm Python-3.5.0]#  
  4. [root@03_sdwm Python-3.5.0]#  
  5. [root@03_sdwm Python-3.5.0]# python3--version  
  6. Python 3.5.0  
  7. [root@03_sdwm Python-3.5.0]#  



2,安装pymongo

安装方法有2种,分别是Installing with pip和Installing with easy_install,这里采用Installing witheasy_install参考官方文章:

http://api.mongodb.com/python/current/installation.html#installing-with-easy-install

安装python pymongo

[python] view plain copy
 
  1. [root@03_sdwm ~]# python3 -m easy_install pymongo  
  2. Searching for pymongo  
  3. Reading http://pypi.python.org/simple/pymongo/  
  4. Best match: pymongo 3.4.0  
  5. Downloading https://pypi.python.org/packages/82/26/f45f95841de5164c48e2e03aff7f0702e22cef2336238d212d8f93e91ea8/pymongo-3.4.0.tar.gz#md5=aa77f88e51e281c9f328cea701bb6f3e  
  6. Processing pymongo-3.4.0.tar.gz  
  7. Running pymongo-3.4.0/setup.py -q bdist_egg --dist-dir /tmp/easy_install-ZZv1Ig/pymongo-3.4.0/egg-dist-tmp-LRDmoy  
  8. zip_safe flag not set; analyzing archive contents...  
  9. Adding pymongo 3.4.0 to easy-install.pth file  
  10.    
  11. Installed /usr/lib/python2.6/site-packages/pymongo-3.4.0-py2.6-linux-x86_64.egg  
  12. Processing dependencies for pymongo  
  13. Finished processing dependencies for pymongo  
  14. [root@03_sdwm ~]#  


 

3,使用pymongo操作mongodb

进行一些简单的对mongodb库的操作
[python] view plain copy
 
    1. #!/usr/bin/env python  
    2. # -*- coding: utf-8 -*-  
    3.    
    4. import pymongo  
    5. import datetime  
    6.    
    7.    
    8. def get_db():  
    9.     # 建立连接  
    10.     client = pymongo.MongoClient(host="10.244.25.180", port=27017)  
    11.     db = client['example']  
    12.     #或者 db = client.example  
    13.     return db  
    14.    
    15.    
    16. def get_collection(db):  
    17.     # 选择集合(mongo中collection和database都是延时创建的)  
    18.     coll = db['informations']  
    19.     print db.collection_names()  
    20.     return coll  
    21.    
    22.    
    23. def insert_one_doc(db):  
    24.     # 插入一个document  
    25.     coll = db['informations']  
    26.     information = {"name": "quyang", "age": "25"}  
    27.     information_id = coll.insert(information)  
    28.     print information_id  
    29.    
    30.    
    31. def insert_multi_docs(db):  
    32.     # 批量插入documents,插入一个数组  
    33.     coll = db['informations']  
    34.     information = [{"name": "xiaoming", "age": "25"}, {"name": "xiaoqiang", "age": "24"}]  
    35.     information_id = coll.insert(information)  
    36.     print information_id  
    37.    
    38.    
    39. def get_one_doc(db):  
    40.     # 有就返回一个,没有就返回None  
    41.     coll = db['informations']  
    42.     print coll.find_one()  # 返回第一条记录  
    43.     print coll.find_one({"name": "quyang"})  
    44.     print coll.find_one({"name": "none"})  
    45.    
    46.    
    47. def get_one_by_id(db):  
    48.     # 通过objectid来查找一个doc  
    49.     coll = db['informations']  
    50.     obj = coll.find_one()  
    51.     obj_id = obj["_id"]  
    52.     print "_id 为ObjectId类型,obj_id:" + str(obj_id)  
    53.    
    54.     print coll.find_one({"_id": obj_id})  
    55.     # 需要注意这里的obj_id是一个对象,不是一个str,使用str类型作为_id的值无法找到记录  
    56.     print "_id 为str类型 "  
    57.     print coll.find_one({"_id": str(obj_id)})  
    58.     # 可以通过ObjectId方法把str转成ObjectId类型  
    59.     from bson.objectid import ObjectId  
    60.    
    61.     print "_id 转换成ObjectId类型"  
    62.     print coll.find_one({"_id": ObjectId(str(obj_id))})  
    63.    
    64.    
    65. def get_many_docs(db):  
    66.     # mongo中提供了过滤查找的方法,可以通过各种条件筛选来获取数据集,还可以对数据进行计数,排序等处理  
    67.     coll = db['informations']  
    68.     #ASCENDING = 1 升序;DESCENDING = -1降序;default is ASCENDING  
    69.     for item in coll.find().sort("age", pymongo.DESCENDING):  
    70.         print item  
    71.    
    72.     count = coll.count()  
    73.     print "集合中所有数据 %s个" % int(count)  
    74.    
    75.     #条件查询  
    76.     count = coll.find({"name":"quyang"}).count()  
    77.     print "quyang: %s"%count  
    78.    
    79. def clear_all_datas(db):  
    80.     #清空一个集合中的所有数据  
    81.     db["informations"].remove()  
    82.    
    83. if __name__ == '__main__':  
    84.     db = get_db()  
    85.     my_collection = get_collection(db)  
    86.     post = {"author": "Mike", "text": "My first blog post!", "tags": ["mongodb", "python", "pymongo"],  
    87.             "date": datetime.datetime.utcnow()}  
    88.     # 插入记录  
    89.     my_collection.insert(post)  
    90.     insert_one_doc(db)  
    91.     # 条件查询  
    92.     print my_collection.find_one({"x": "10"})  
    93.     # 查询表中所有的数据  
    94.     for iii in my_collection.find():  
    95.         print iii  
    96.     print my_collection.count()  
    97.     my_collection.update({"author": "Mike"},  
    98.                          {"author": "quyang", "text": "My first blog post!", "tags": ["mongodb", "python", "pymongo"],  
    99.                           "date": datetime.datetime.utcnow()})  
    100.     for jjj in my_collection.find():  
    101.         print jjj  
    102.     get_one_doc(db)  
    103.     get_one_by_id(db)  
    104.     get_many_docs(db)  
    105.     # clear_all_datas(db)  
原文地址:https://www.cnblogs.com/RandomRand/p/7784543.html