MongoDbエッセイ、PyMongo簡単に使用

18096 ワード

MongoDbのインストール
MongoDbは、対応するシステムバージョンの実行可能ファイルをダウンロードします.本人システム環境:rhel-server-6.2-x 86_64解凍パックtar zxvf mongodb-linux-x86_64-rhel62-3.0.2.tgzディレクトリの下のREADMEを見て、各実行可能ファイルの役割を知ることができます.簡単な起動コマンドmkdir db; mongo --dbpath=./db mongo --helpは、より多くのヘルプを得ることができます.起動パラメータリファレンスを変更するプロファイルを指定することもできますhttps://docs.mongodb.com/manual/reference/configuration-options/#configuration-file
PyMongoのインストール
インストールコマンド:pip install pymongo pipの詳細については、Pythonのpip pydoc 2 to 3などのツールを参照してください.
PyMongoシンプル
#!/usr/bin/env python
# -*- coding: utf-8 -*-

import pymongo
import datetime


def get_db():
    #     
    client = pymongo.MongoClient(host="10.244.25.180", port=27017)
    db = client['example']
    #   db = client.example
    return db


def get_collection(db):
    #     (mongo collection database       )
    coll = db['informations']
    print db.collection_names()
    return coll


def insert_one_doc(db):
    #     document
    coll = db['informations']
    information = {"name": "quyang", "age": "25"}
    information_id = coll.insert(information)
    print information_id


def insert_multi_docs(db):
    #     documents,      
    coll = db['informations']
    information = [{"name": "xiaoming", "age": "25"}, {"name": "xiaoqiang", "age": "24"}]
    information_id = coll.insert(information)
    print information_id


def get_one_doc(db):
    #       ,     None
    coll = db['informations']
    print coll.find_one()  #        
    print coll.find_one({"name": "quyang"})
    print coll.find_one({"name": "none"})


def get_one_by_id(db):
    #   objectid     doc
    coll = db['informations']
    obj = coll.find_one()
    obj_id = obj["_id"]
    print "_id  ObjectId  ,obj_id:" + str(obj_id)

    print coll.find_one({"_id": obj_id})
    #        obj_id     ,    str,  str    _id        
    print "_id  str   "
    print coll.find_one({"_id": str(obj_id)})
    #     ObjectId   str  ObjectId  
    from bson.objectid import ObjectId

    print "_id    ObjectId  "
    print coll.find_one({"_id": ObjectId(str(obj_id))})


def get_many_docs(db):
    # mongo           ,                ,          ,     
    coll = db['informations']
    #ASCENDING = 1   ;DESCENDING = -1  ;default is ASCENDING
    for item in coll.find().sort("age", pymongo.DESCENDING):
        print item

    count = coll.count()
    print "        %s " % int(count)

    #    
    count = coll.find({"name":"quyang"}).count()
    print "quyang: %s"%count

def clear_all_datas(db):
    #            
    db["informations"].remove()

if __name__ == '__main__':
    db = get_db()
    my_collection = get_collection(db)
    post = {"author": "Mike", "text": "My first blog post!", "tags": ["mongodb", "python", "pymongo"],
            "date": datetime.datetime.utcnow()}
    #     
    my_collection.insert(post)
    insert_one_doc(db)
    #     
    print my_collection.find_one({"x": "10"})
    #          
    for iii in my_collection.find():
        print iii
    print my_collection.count()
    my_collection.update({"author": "Mike"},
                         {"author": "quyang", "text": "My first blog post!", "tags": ["mongodb", "python", "pymongo"],
                          "date": datetime.datetime.utcnow()})
    for jjj in my_collection.find():
        print jjj
    get_one_doc(db)
    get_one_by_id(db)
    get_many_docs(db)
    # clear_all_datas(db)

生産資源要約
  • インストールパッケージダウンロードリンクhttps://www.mongodb.com/download-center#community
  • 公式マニュアルhttps://docs.mongodb.com/manual/

  • チュートリアル:
  • MongoDBチュートリアル