MongoDb隨筆,PyMongo簡單使用

來源:互聯網
上載者:User

標籤:pymongo   mongodb安裝   

安裝MongoDb

MongoDb下載對應的系統版本的可執行檔
本人系統內容:rhel-server-6.2-x86_64
解壓縮包tar zxvf mongodb-linux-x86_64-rhel62-3.0.2.tgz

可以查看目錄下的README,瞭解各個可執行檔的作用。
簡單啟動命令 mkdir db; mongo --dbpath=./db
mongo --help 可以擷取更多協助。

安裝PyMongo

安裝命令:pip install pymongo
更多關於pip的應用可參考Python下pip pydoc 2to3等工具

PyMongo簡單使用
#!/usr/bin/env python# -*- coding: utf-8 -*-import pymongoimport datetimedef get_db():    # 建立串連    client = pymongo.MongoClient(host="10.244.25.180", port=27017)    db = client[‘example‘]    #或者 db = client.example    return dbdef get_collection(db):    # 選擇集合(mongo中collection和database都是延時建立的)    coll = db[‘informations‘]    print db.collection_names()    return colldef insert_one_doc(db):    # 插入一個document    coll = db[‘informations‘]    information = {"name": "quyang", "age": "25"}    information_id = coll.insert(information)    print information_iddef insert_multi_docs(db):    # 批量插入documents,插入一個數組    coll = db[‘informations‘]    information = [{"name": "xiaoming", "age": "25"}, {"name": "xiaoqiang", "age": "24"}]    information_id = coll.insert(information)    print information_iddef 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"%countdef 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)

MongoDb隨筆,PyMongo簡單使用

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.