1. 程式人生 > >Python 使用pymongo操作mongodb庫

Python 使用pymongo操作mongodb庫

演示 clear bject conf dconf www. pda des tails

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. Installed /usr/lib/python2.6/site-packages/pymongo-3.4.0-py2.6-linux-x86_64.egg
  11. Processing dependencies for pymongo
  12. Finished processing dependencies for pymongo
  13. [root@03_sdwm ~]#


3,使用pymongo操作mongodb

進行一些簡單的對mongodb庫的操作

[python] view plain copy
    1. #!/usr/bin/env python
    2. # -*- coding: utf-8 -*-
    3. import pymongo
    4. import datetime
    5. def get_db():
    6. # 建立連接
    7. client = pymongo.MongoClient(host="10.244.25.180", port=27017)
    8. db = client[‘example‘]
    9. #或者 db = client.example
    10. return db
    11. def get_collection(db):
    12. # 選擇集合(mongo中collection和database都是延時創建的)
    13. coll = db[‘informations‘]
    14. print db.collection_names()
    15. return coll
    16. def insert_one_doc(db):
    17. # 插入一個document
    18. coll = db[‘informations‘]
    19. information = {"name": "quyang", "age": "25"}
    20. information_id = coll.insert(information)
    21. print information_id
    22. def insert_multi_docs(db):
    23. # 批量插入documents,插入一個數組
    24. coll = db[‘informations‘]
    25. information = [{"name": "xiaoming", "age": "25"}, {"name": "xiaoqiang", "age": "24"}]
    26. information_id = coll.insert(information)
    27. print information_id
    28. def get_one_doc(db):
    29. # 有就返回一個,沒有就返回None
    30. coll = db[‘informations‘]
    31. print coll.find_one() # 返回第一條記錄
    32. print coll.find_one({"name": "quyang"})
    33. print coll.find_one({"name": "none"})
    34. def get_one_by_id(db):
    35. # 通過objectid來查找一個doc
    36. coll = db[‘informations‘]
    37. obj = coll.find_one()
    38. obj_id = obj["_id"]
    39. print "_id 為ObjectId類型,obj_id:" + str(obj_id)
    40. print coll.find_one({"_id": obj_id})
    41. # 需要註意這裏的obj_id是一個對象,不是一個str,使用str類型作為_id的值無法找到記錄
    42. print "_id 為str類型 "
    43. print coll.find_one({"_id": str(obj_id)})
    44. # 可以通過ObjectId方法把str轉成ObjectId類型
    45. from bson.objectid import ObjectId
    46. print "_id 轉換成ObjectId類型"
    47. print coll.find_one({"_id": ObjectId(str(obj_id))})
    48. def get_many_docs(db):
    49. # mongo中提供了過濾查找的方法,可以通過各種條件篩選來獲取數據集,還可以對數據進行計數,排序等處理
    50. coll = db[‘informations‘]
    51. #ASCENDING = 1 升序;DESCENDING = -1降序;default is ASCENDING
    52. for item in coll.find().sort("age", pymongo.DESCENDING):
    53. print item
    54. count = coll.count()
    55. print "集合中所有數據 %s個" % int(count)
    56. #條件查詢
    57. count = coll.find({"name":"quyang"}).count()
    58. print "quyang: %s"%count
    59. def clear_all_datas(db):
    60. #清空一個集合中的所有數據
    61. db["informations"].remove()
    62. if __name__ == ‘__main__‘:
    63. db = get_db()
    64. my_collection = get_collection(db)
    65. post = {"author": "Mike", "text": "My first blog post!", "tags": ["mongodb", "python", "pymongo"],
    66. "date": datetime.datetime.utcnow()}
    67. # 插入記錄
    68. my_collection.insert(post)
    69. insert_one_doc(db)
    70. # 條件查詢
    71. print my_collection.find_one({"x": "10"})
    72. # 查詢表中所有的數據
    73. for iii in my_collection.find():
    74. print iii
    75. print my_collection.count()
    76. my_collection.update({"author": "Mike"},
    77. {"author": "quyang", "text": "My first blog post!", "tags": ["mongodb", "python", "pymongo"],
    78. "date": datetime.datetime.utcnow()})
    79. for jjj in my_collection.find():
    80. print jjj
    81. get_one_doc(db)
    82. get_one_by_id(db)
    83. get_many_docs(db)
    84. # clear_all_datas(db)

Python 使用pymongo操作mongodb庫